...

C# 客戶端程序調用外部程序的(de)3種實現方法

2022-01-30

前言

文章主要(yào / yāo)給大(dà)家介紹關于(yú) C# 客戶端程序調用外部程序的(de) 3 種實現方法,文中通過示例代碼介紹的(de)非常詳細,對大(dà)家的(de)學習或者工作具有一(yī / yì /yí)定的(de)參考學習價值。

簡介

大(dà)家都知道(dào),當我們用 C# 來(lái)開發客戶端程序的(de)時(shí)候,總會不(bù)可避免的(de)需要(yào / yāo)調用外部程序或者訪問網站,本文介紹了(le/liǎo)三種調用外部應用的(de)方法,供參考,下面話不(bù)多說(shuō)了(le/liǎo),來(lái)一(yī / yì /yí)起看看詳細的(de)介紹吧。

實現

第一(yī / yì /yí)種利用 shell32.dll

實現 ShellExecute 方法,該方法可同時(shí)打開本地(dì / de)程序、文件夾或者訪問網站,隻要(yào / yāo)直接輸入路徑字符串即可, 如 C:\Users\Desktop\xx.exe 或者 https://cn.bing.com/,可以(yǐ)根據返回值判斷是(shì)否調用成功 (成功0x00000002a , 失敗0x00000002)

Window wnd = Window.GetWindow(this); //獲取當前窗口
var wih = new WindowInteropHelper(wnd); //該類支持獲取hWnd
IntPtr hWnd = wih.Handle;    //獲取窗口句柄
var result = ShellExecute(hWnd, "open""需要(yào / yāo)打開的(de)路徑如C:\Users\Desktop\xx.exe"nullnull, (int)ShowWindowCommands.SW_SHOW);
[DllImport("shell32.dll")]
public static extern IntPtr ShellExecute(IntPtr hwnd, //窗口句柄
 string lpOperation, //指定要(yào / yāo)進行的(de)操作
 string lpFile,  //要(yào / yāo)執行的(de)程序、要(yào / yāo)浏覽的(de)文件夾或者網址
 string lpParameters, //若lpFile參數是(shì)一(yī / yì /yí)個(gè)可執行程序,則此參數指定命令行參數
 string lpDirectory, //指定默認目錄
 int nShowCmd   //若lpFile參數是(shì)一(yī / yì /yí)個(gè)可執行程序,則此參數指定程序窗口的(de)初始顯示方式(參考如下枚舉)
 )
;
public enum ShowWindowCommands : int
{
 SW_HIDE = 0,
 SW_SHOWNORMAL = 1,
 SW_NORMAL = 1,
 SW_SHOWMINIMIZED = 2,
 SW_SHOWMAXIMIZED = 3,
 SW_MAXIMIZE = 3,
 SW_SHOWNOACTIVATE = 4,
 SW_SHOW = 5,  //顯示一(yī / yì /yí)個(gè)窗口,同時(shí)令其進入活動狀态
 SW_MINIMIZE = 6,
 SW_SHOWMINNOACTIVE = 7,
 SW_SHOWNA = 8,
 SW_RESTORE = 9,
 SW_SHOWDEFAULT = 10,
 SW_MAX = 10
}

第二種是(shì)利用 kernel32.dll

實現 WinExec 方法,該方法僅能打開本地(dì / de)程序,可以(yǐ)根據返回值判斷是(shì)否調用成功(<32表示出(chū)現錯誤)

var result = WinExec(pathStr, (int)ShowWindowCommands.SW_SHOW);
[DllImport("kernel32.dll")]
public static extern int WinExec(string programPath, int operType);

第三種方法是(shì)利用 Process 類

Process 類具體應用可以(yǐ)看類的(de)定義,這(zhè)裏隻實現它打開文件和(hé / huò)訪問網站的(de)用法,調用失敗會抛出(chū)異常

/// <devdoc>
/// <para>
///  Provides access to local and remote
///  processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>

具體實現爲(wéi / wèi)

//調用程序  
Process process = new Process();
try
 {
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.FileName = pathStr;
  process.StartInfo.CreateNoWindow = true;
  process.Start();
 }
  catch (Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
//訪問網站
try
{
  Process.Start("iexplore.exe", pathStr);
}
  catch (Exception ex)
{
  MessageBox.Show(ex.Message);
}

- EOF -


來(lái)源:DotNet