C# Shell 调用外部程序方法

In this article we will examine a few examples for executing shell commands outside of our program using C#. In VB.Net, we can make use of the familiar Shell command to run an executable program. However the Shell function is not available in C#. The Process Class provides access to local and remote processes and enables you to start and stop local system processes.

In our example we will create an example for running the following processes from our program.

  1. Calculator
  2. DOS Batch program - Map a network drive
  3. Internet explorer with a specified URL
  4. Specified Document in Microsoft Word.

C# Application

Our basic application is a Winforms Visual C# application and will consist of a Windows Form with button controls to invoke the processes specified in the list. (The complete code for the application is provided at the bottom of the article).

Add button controls from the toolbox as shown in the figure below.

Figure 1: Basic Windows Form

Calculator

The option to provide a calculator to the end user on the click of a button can be very useful. The calculator program can be invoked from command line using the command "calc".

Add the following code to the event handler for the button's Click event as shown below. Details explaining the code follow the code listing.

We create a new Process and assign the FileName variable to the name of the executable that we want to run. The Start() method of the Process object starts the specified application and assigns it to the process component.

Figure: Calculator is invoked when the Calculator button is clicked.

Map a network Drive

We will invoke a DOS batch script which will map a network drive for us. The DOS command for mapping a drive is as follows:

NET USE <DriveName>: \\<RemoteServer>\<SharedFolder> /User:<Domain>\<UserName> <password> /PERSISTENT:YES

Note : Ensure that the drive mapping is not already in use.

Create a text file containing the above command and Save the file as netdrv.bat. I saved the file in folder c:\dotnetstuff\netdrv.bat.

Here is the format of the command contained in the netdrv.bat file.

NET USE U: \\master\testshare /User:Enterprise\dchoksi passwd /PERSISTENT:YES

Add the following code to the button click event handler of the button labeled "Map Network Drive".

Microsoft.com

We will create a button that will take the user to the Microsoft.com web site. This logic can be used to open up a registration form for product registration or to point to online help in Windows forms products.

Add the following code in the button Click event handler :

Note that the code waits for the Internet Explorer process to exit and then proceeds to display the messagebox. This is achieved through the use of the WaitForExit() function of the Process object.

Open a specific document in Microsoft Word.

Add the following code to the button's OnClick event handler.

Note that the name of the Word document to open is specified in the Arguments for the StartInfo of the Process.

Complete Code Listing:
System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace ShellCS_NS
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
public
Form1()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(16, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 72);
this.button1.TabIndex = 0;
this.button1.Text = "Calculator";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button2.Location = new System.Drawing.Point(16, 120);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(112, 72);
this.button2.TabIndex = 1;
this.button2.Text = "Map Network Drive";
this.button2.Click += new System.EventHandler(this.button2_Click);
this.button3.Location = new System.Drawing.Point(168, 24);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(112, 72);
this.button3.TabIndex = 2;
this.button3.Text = "Microsoft.com";
this.button3.Click += new System.EventHandler(this.button3_Click);
this.button4.Location = new System.Drawing.Point(168, 120);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(112, 64);
this.button4.TabIndex = 3;
this.button4.Text = "My Word Document";
this.button4.Click += new System.EventHandler(this.button4_Click);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 213);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button4, this.button3, this.button2, this.button1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
[STAThread]
static void Main()
{
Application.Run(
new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="calc";
proc.Start();
}
private void button2_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="c:\\dotnetstuff\\NETDRV.bat";
proc.Start();
MessageBox.Show("Map Drive Created");
}
private void button3_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments=http://www.microsoft.com;
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited www.microsoft.com");
}
private void button4_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="winword";
proc.StartInfo.Arguments="C:\\Dotnetstuff\\TestWordDoc.doc";
proc.Start();
}
}
}

Code Listing: Shellcs.cs

NET USE U: \\master\testshare
/User:Enterprise\dchoksi passwd /PERSISTENT:YES

Code Listing : Netdrv.bat

using

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="winword";
proc.StartInfo.Arguments="C:\\Dotnetstuff\\TestWordDoc.doc";
proc.Start();
Code Listing : Open specific Word Document System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments=
http://www.microsoft.com ;
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited www.microsoft.com");
Code Listing: Microsoft.com System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="c:\\dotnetstuff\\netdrv.bat";
proc.Start();
MessageBox.Show("Map Drive Created");
Code Listing: This code will execute the dos batch file and U:\ is mapped to the remote share \\master\testshare. System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="calc";
proc.Start();
Code Listing: Invoke the calculator from a C# program
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#调用Python程序可以通过以下步骤实现: 1. 首先,将Python程序转换为动态链接库(dll)。这可以通过使用Cython或者使用Python的ctypes库来实现。在转换为dll之前,确保已经安装了Python运行环境,并且安装了所需的第三方库(如numpy)\[1\]。 2. 在C#中,使用DllImport特性来导入Python的dll文件。这样可以在C#调用Python的函数。确保在C#项目中引用了Python的dll文件。 3. 在C#调用Python函数时,需要传递参数并接收返回值。可以使用C#的InteropServices命名空间中的Marshal类来处理参数和返回值的转换。 下面是一个示例代码,演示了如何在C#调用Python程序: ```csharp using System; using System.Runtime.InteropServices; public class Program { \[DllImport("python_dll_path", CallingConvention = CallingConvention.Cdecl)\] public static extern double func(string a, string b); public static void Main(string\[\] args) { string a = "2"; string b = "3"; double result = func(a, b); Console.WriteLine(result); } } ``` 在上面的代码中,`python_dll_path`是Python程序转换为的dll文件的路径。`func`是Python程序中的函数名,通过DllImport特性导入。 请注意,这只是一个简单的示例,实际情况可能会更复杂。在实际使用中,还需要处理异常、错误检查等情况。 希望这个回答对您有帮助!\[1\] #### 引用[.reference_title] - *1* [c#调用python的四种方法(尝试了四种,只详细讲解本人成功的后两种,其余方法只列出,详细用法请自行谷歌...](https://blog.csdn.net/qq_42063091/article/details/82418630)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [c#调用python的三种方法](https://blog.csdn.net/qq_36744449/article/details/116134794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值