C# winform 启动外部程序的三种方式

启用外部程序有很多方法,我自己要启动的程序因为内部调用了第三方的驱动,通过其它的调用方法均无法完美打开,始终有功能缺陷

下面介绍几种可打开的方式:

通过内置 Process 方式打开程序

1 Process m_Process = null;
2 m_Process = new Process();
3 m_Process.StartInfo.FileName = @"C:\test.exe";
4 m_Process.Start();

通过win32 ,设置桌面鼠标位置,通过方法模拟鼠标双击事件

 1 //在class下面放入以下方法
 2 //绑定事件
 3 [System.Runtime.InteropServices.DllImport("user32")]
 4 private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
 5 
 6 //定位
 7 [DllImport("User32")]
 8 public extern static void SetCursorPos(int x, int y);  
 9 
10 
11 
12 //代码放在需要执行的地方
13 const int MOUSEEVENTF_LEFTDOWN = 0x0002;
14 const int MOUSEEVENTF_LEFTUP = 0x0004;
15 SetCursorPos(33, 28);
16 
17 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
18 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

shell32.dll 方法

1 //class里面放入这段代码
2 [DllImport("shell32.dll")]
3 public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
4 
5 
6 //需要打开的地方插入此段代码
7   ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder("test.exe"), new StringBuilder(""), new StringBuilder(@"C:\文件夹名"), 1);

以上三种方法,都能实现从winform打开外部程序

第一种最方便,但是调用的外部程序中如果有使用第三方或系统插件时是无法调用起来的,今天我这里就不行

第二种是通过设置鼠标在桌面中的位置,模拟双击事件,这种方式虽然可行,但是当服务器锁屏或者需要双击的位置被其它文件覆盖时则无法达到预期效果

第三种是都可以的,缺点目前还没有发现,匆匆弄好就没注意看了。

猜你喜欢

转载自www.cnblogs.com/chonglu/p/12972429.html
今日推荐