C#实现进程管理的启动和停止实例
本文实例讲述了C#实现进程管理的启动和停止方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
//引用命名空间
usingSystem.Diagnostics;
usingSystem.Threading;
namespaceStartStopProcess
{
publicpartialclassForm1:Form
{
intfileIndex;
stringfileName="Notepad.exe";
Processprocess1=newProcess();
publicForm1()
{
InitializeComponent();
//以详细列表方式显示
listView1.View=View.Details;
//参数含义:列名称,宽度(像素),水平对齐方式
listView1.Columns.Add("进程ID",70,HorizontalAlignment.Left);
listView1.Columns.Add("进程名称",70,HorizontalAlignment.Left);
listView1.Columns.Add("占用内存",70,HorizontalAlignment.Left);
listView1.Columns.Add("启动时间",70,HorizontalAlignment.Left);
listView1.Columns.Add("文件名",280,HorizontalAlignment.Left);
}
privatevoidbuttonStart_Click(objectsender,EventArgse)
{
stringargument=Application.StartupPath+"\\myfile"+fileIndex+".txt";
if(File.Exists(argument)==false)
{
File.CreateText(argument);
}
//设置要启动的应用程序名称及参数
ProcessStartInfops=newProcessStartInfo(fileName,argument);
ps.WindowStyle=ProcessWindowStyle.Normal;
fileIndex++;
Processp=newProcess();
p.StartInfo=ps;
p.Start();
//等待启动完成,否则获取进程信息可能会失败
p.WaitForInputIdle();
RefreshListView();
}
privatevoidbuttonStop_Click(objectsender,EventArgse)
{
this.Cursor=Cursors.WaitCursor;
//创建新的Process组件的数组,并将它们与指定的进程名称(Notepad)的所有进程资源相关联.
Process[]myprocesses;
myprocesses=Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
foreach(Processpinmyprocesses)
{
//通过向进程主窗口发送关闭消息达到关闭进程的目的
p.CloseMainWindow();
//等待1000毫秒
Thread.Sleep(1000);
//释放与此组件关联的所有资源
p.Close();
}
fileIndex=0;
RefreshListView();
this.Cursor=Cursors.Default;
}
privatevoidRefreshListView()
{
listView1.Items.Clear();
//创建Process类型的数组,并将它们与系统内所有进程相关联
Process[]processes;
processes=Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
foreach(Processpinprocesses)
{
//将每个进程的进程名称、占用的物理内存以及进程开始时间加入listView中
ListViewItemitem=newListViewItem(
newstring[]{
p.Id.ToString(),
p.ProcessName,
string.Format("{0}KB",p.PrivateMemorySize64/1024.0f),
string.Format("{0}",p.StartTime),
p.MainModule.FileName
});
listView1.Items.Add(item);
}
}
privatevoidbuttonRefresh_Click(objectsender,EventArgse)
{
RefreshListView();
}
privatevoidForm1_Load(objectsender,EventArgse)
{
}
}
}
希望本文所述对大家的C#程序设计有所帮助。