C# 启动和关闭 外部应用程序

本文介绍了C#如何启动和关闭外部应用程序,包括不等待、等待指定时间和无限等待程序退出的三种启动方式,并提供了关闭程序的方法,强调了代码的健壮性和可扩展性。通过Process类的使用,实现对外部程序的管理和控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C# 启动和关闭外部应用程序

描述

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;
}

关闭外部程序很简单,但为什么写这么多代码,不觉得繁琐吗。其实不然,这样写的好处有两点:

  • 可以增强我们的代码的健壮性;
  • 可扩展性;

上述代码中关闭程序是同时使用了两种哦,这种写法,极大地增强了代码的健壮性,是我们的程序几乎处于永远不崩溃之地。

这里呢我也只是粗略的使用,有兴趣的同学可以深入的研究下。

这个库也经常被用来监控程序的运行状况哦!😃😃😃

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑夜中的潜行者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值