代码改变世界

C# 启动与停止进程

2011-12-02 01:04  Andrew.Wangxu  阅读(532)  评论(3编辑  收藏  举报

也是书中《C#网络应用编程》的一章。方便日后翻用。

该例子为 notepad.exe (记事本)程序的启动与结束

 

引用命名空间:

using System.Diagnostics;  
using System.IO;

 

 

namespace StartStopProcess  
{
public partial class Form1 : Form
{
int fileIndex;
string fileName = "notepad.exe";
Process process1 = new Process();
public Form1()
{
InitializeComponent();
}

private void LoadProcessToControl()
{
lvw_Process.Items.Clear();
Process[] processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
foreach (Process p in processes)
{
ListViewItem item = new ListViewItem(
new string[]{
p.Id.ToString(),
p.ProcessName,
string.Format("{0}KB",p.WorkingSet64 / 1024f),
string.Format("{0}",p.StartTime),
p.MainModule.FileName
});
lvw_Process.Items.Add(item);
}
}

private void Form1_Load(object sender, EventArgs e)
{
LoadProcessToControl();
}

private void btn_StartProcess_Click(object sender, EventArgs e)
{
string argument = Application.StartupPath + "\\myfile" + fileIndex + ".txt";
if (!File.Exists(argument))
{
File.CreateText(argument);
}
ProcessStartInfo ps = new ProcessStartInfo(fileName, argument);
ps.WindowStyle = ProcessWindowStyle.Normal;
fileIndex++;
Process p = new Process();
p.StartInfo = ps;
p.Start();
//等待启动完成,否则获取进程信息可能会失败
p.WaitForInputIdle();
LoadProcessToControl();
}

private void btn_StopProcess_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
Process[] myprocesses = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
foreach (Process p in myprocesses)
{
p.CloseMainWindow();
p.WaitForExit(5000); //设置最多等待5秒(处理类似用于需要用户确定关闭的对话框未关闭的情况)
p.Close();
}
fileIndex = 0;
LoadProcessToControl();
this.Cursor = Cursors.Default;
}


}
}

 

截图:

 


参考:http://www.wxzzz.com/?id=15