栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

描述

C# 启动外部应用程序还是很简洁方便的。
需要注意的是,外部程序的路径问题:

  • appName = "xxx.exe" 或
  • appName = "xxx/xxx.exe"

所在程序集:using System.Diagnostics

同理C# 关闭外部应用程序也是这样,不过这里提供一种相对较好的方式,下面会讲解为什么这样用。

启动外部应用程序

这里提供三种方案,当然也有其他的方案,只是我认为这三种相对更好一点。

using System.Diagnostics;

/// 
/// 1. 启动外部程序,不等待其退出
/// 
public bool ProgramStart(string appName)
{
    try
    {
        Process.Start(appName);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return false;
}

/// 
/// 2. 启动外部程序,等待其退出
/// 
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;
}

/// 
/// 3. 启动外部程序,无限等待其退出
/// 
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;
}

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

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

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号