C# winform 啟動外部程序的三種方式


啟用外部程序有很多方法,我自己要啟動的程序因為內部調用了第三方的驅動,通過其它的調用方法均無法完美打開,始終有功能缺陷

下面介紹幾種可打開的方式:

通過內置 Process 方式打開程序

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

通過win32 ,設置桌面鼠標位置,通過方法模擬鼠標雙擊事件

//在class下面放入以下方法
//綁定事件
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

//定位
[DllImport("User32")]
public extern static void SetCursorPos(int x, int y);  
 

//代碼放在需要執行的地方
const int MOUSEEVENTF_LEFTDOWN = 0x0002;
const int MOUSEEVENTF_LEFTUP = 0x0004;
SetCursorPos(33, 28);

mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

shell32.dll 方法

//class里面放入這段代碼
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

//需要打開的地方插入此段代碼
ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder("test.exe"), new StringBuilder(""), new StringBuilder(@"C:\文件夾名"), 1);

 

以上三種方法,都能實現從winform打開外部程序

第一種最方便,但是調用的外部程序中如果有使用第三方或系統插件時是無法調用起來的,今天我這里就不行

第二種是通過設置鼠標在桌面中的位置,模擬雙擊事件,這種方式雖然可行,但是當服務器鎖屏或者需要雙擊的位置被其它文件覆蓋時則無法達到預期效果

第三種是都可以的,缺陷是無法關閉它,需要自己再另外處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM