描述
C# 启动外部应用程序还是很简洁方便的。
需要注意的是,外部程序的路径问题:
appName = "xxx.exe"
或appName = "xxx/xxx.exe"
所在程序集:
using System.Diagnostics
同理C# 关闭外部应用程序也是这样,不过这里提供一种相对较好的方式,下面会讲解为什么这样用。
启动外部应用程序
这里提供三种方案,当然也有其他的方案,只是我认为这三种相对更好一点。
using System.Diagnostics;
/// <summary>
/// 1. 启动外部程序,不等待其退出
/// </summary>
public bool ProgramStart(string appName)
{
try
{
Process.Start(appName);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
/// <summary>
/// 2. 启动外部程序,等待其退出
/// </summary>
public bool ProgramStart(string appName)
{
try
{
Process proc = Process.Start(appName);
if (proc != null)
{
proc.WaitForExit(3000);
if (proc.HasExited) return true;
else
{
// 如果外部程序没有结束运行则强行终止之。
proc.Kill();
return true;
}
}
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
/// <summary>
/// 3. 启动外部程序,无限等待其退出
/// </summary>
public bool ProgramStart(string appName)
{
try
{
Process proc = Process.Start(appName);
if (proc != null)
{
proc.WaitForExit();
Console.WriteLine($"外部程序 {appName}已经退出!");
return true;
}
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
关闭外部应用程序
using System.Collections;
using System.Diagnostics;
public bool CloseProc(string procName)
{
bool result = false;
ArrayList procList = new ArrayList();
string tempName;
int begpos;
int endpos;
foreach (Process thisProc in Process.GetProcesses())
{
tempName = thisProc.ToString();
begpos = tempName.IndexOf("(") + 1;
endpos = tempName.IndexOf(")");
tempName = tempName[begpos..endpos];
procList.Add(tempName);
if (tempName == ProcName)
{
if (!thisProc.CloseMainWindow())
// 当发送关闭窗口命令无效时强行结束进程
thisProc.Kill();
result = true;
}
}
return result;
}
关闭外部程序很简单,但为什么写这么多代码,不觉得繁琐吗。其实不然,这样写的好处有两点:
- 可以增强我们的代码的健壮性;
- 可扩展性;
上述代码中关闭程序是同时使用了两种哦,这种写法,极大地增强了代码的健壮性,是我们的程序几乎处于永远不崩溃之地。
这里呢我也只是粗略的使用,有兴趣的同学可以深入的研究下。
这个库也经常被用来监控程序的运行状况哦!😃😃😃