把写内容过程中经常用到的内容做个收藏,如下的内容是关于C#只启动一个进程的内容。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Process currentProcess = Process.GetCurrentProcess();
foreach (Process item in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (item.Id != currentProcess.Id &&
(item.StartTime - currentProcess.StartTime).TotalMilliseconds <= 0)
{
item.Kill();
item.WaitForExit();
break;
}
}
base.OnStartup(e);
}
}
对于Winform的则直接在主窗体的构造其中判断。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartUp();
}
private void StartUp()
{
Process currentProcess = Process.GetCurrentProcess();
foreach (Process item in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (item.Id != currentProcess.Id &&
(item.StartTime - currentProcess.StartTime).TotalMilliseconds <= 0)
{
item.Kill();
item.WaitForExit();
break;
}
}
}
}
简单的代码就可以完成这个功能。