随笔 - 3461, 文章 - 0, 评论 - 739, 阅读 - 1200万
  管理

C# 启动外部程序的几种方法

Posted on   lzhdim  阅读(278)  评论(0编辑  收藏  举报

1. 启动外部程序,不等待其退出。 
2. 启动外部程序,等待其退出。 
3. 启动外部程序,无限等待其退出。 
4. 启动外部程序,通过事件监视其退出。

 
// using System.Diagnostics;

private string appName = "calc.exe";

/// <summary>

/// 1. 启动外部程序,不等待其退出

/// </summary>

private void button1_Click(object sender, EventArgs e)
{
Process.Start(appName);
MessageBox.Show(String.Format("外部程序 {0} 启动完成!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

/// <summary>

/// 2. 启动外部程序,等待其退出

/// </summary>

private void button2_Click(object sender, EventArgs e)
{
try
{
Process proc = Process.Start(appName);
if (proc != null)
{
proc.WaitForExit(3000);
if (proc.HasExited)
MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
// 如果外部程序没有结束运行则强行终止之。

proc.Kill();
MessageBox.Show(String.Format("外部程序 {0} 被强行终止!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message, this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}


/// <summary>

/// 3. 启动外部程序,无限等待其退出

/// </summary>

private void button3_Click(object sender, EventArgs e)
{
try
{
Process proc = Process.Start(appName);
if (proc != null)
{
proc.WaitForExit();
MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message, this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}


/// <summary>

/// 4. 启动外部程序,通过事件监视其退出

/// </summary>

private void button4_Click(object sender, EventArgs e)
{
try
{
// 启动外部程序

Process proc = Process.Start(appName);
if (proc != null)
{
// 监视进程退出

proc.EnableRaisingEvents = true;
// 指定退出事件方法

proc.Exited += new EventHandler(proc_Exited);
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message, this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>

/// 启动外部程序退出事件

/// </summary>

void proc_Exited(object sender, EventArgs e)
{
MessageBox.Show(String.Format("外部程序 {0} 已经退出!", this.appName), this.Text,
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2008-12-05 开发框架之我Spring纯在的一些负面因素
Copyright (C) 2000-2025 Lzhdim Software All Rights Reserved
点击右上角即可分享
微信分享提示