C#启动一个外部程序,2-ShellExecute

调用Win32 API。

1.

using System.Runtime.InteropServices;

2.

[DllImport("shell32.dll")]

public static extern int ShellExecute(IntPtr hwnd,StringBuilder lpszOp,StringBuilder lpszFile,StringBuilder lpszParams,StringBuilder lpszDir,int FsShowCmd);

3.调用,打开记事本:

int a = ShellExecute(IntPtr.Zero,new StringBuilder("Open"),new StringBuilder("notepad"),new StringBuilder(""),new StringBuilder(@"C:\"), 1);

System.Windows.Forms.MessageBox.Show(a.ToString());

4.打开一个网页:

ShellExecute(IntPtr.Zero,new StringBuilder("Open"),new StringBuilder("http://yao.cnblogs.com/"),new StringBuilder(""),new StringBuilder(""), 1);

ShellExecute函数原型及参数含义如下:

  function ShellExecute(hWnd: HWND; Operation, FileName, Parameters,Directory: PChar; ShowCmd: Integer): HINST; stdcall;

  ●hWnd:用于指定父窗口句柄。当函数调用过程出现错误时,它将作为Windows消息窗口的父窗口。例如,可以将其设置为应用程序主窗口句柄,即Application.Handle,也可以将其设置为桌面窗口句柄(用GetDesktopWindow函数获得)。

  ●Operation:用于指定要进行的操作。其中“open”操作表示执行由FileName参数指定的程序,或打开由FileName参数指定的文件或文件夹;“print”操作表示打印由FileName参数指定的文件;“explore”操作表示浏览由FileName参数指定的文件夹。当参数设为nil时,表示执行默认操作“open”。

  ●FileName:用于指定要打开的文件名、要执行的程序文件名或要浏览的文件夹名。

  ●Parameters:若FileName参数是一个可执行程序,则此参数指定命令行参数,否则此参数应为nil或PChar(0)。

  ●Directory:用于指定默认目录。

  ●ShowCmd:若FileName参数是一个可执行程序,则此参数指定程序窗口的初始显示方式,否则此参数应设置为0。此参数更详细说明见:C#启动一个外部程序(1)

  若ShellExecute函数调用成功,则返回值为被执行程序的实例句柄。若返回值小于32,则表示出现错误。