保證軟件只運行一次還是很有必要的,方法也很簡單,只要判斷進程中有無當前的進程名就可以了。 對於WPF的軟件,在App.XAML.cs中判斷。重寫OnStartup方法就可以了。 [csharp] public partial class App : Application { /// <summary> /// 只打開一個進程 /// </summary> /// <param name="e"></param> 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); } } public partial class App : Application { /// <summary> /// 只打開一個進程 /// </summary> /// <param name="e"></param> 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的則直接在主窗體的構造其中判斷。 [csharp] 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; } } } } 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; } } } }簡單的代碼就可以完成這個功能。 追加部分: 如果想做的更嚴格一些,可以根據進程名的路徑來判斷: [csharp] www.2cto.com Process[] sameProcess = Process.GetProcessesByName (Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.BaseDirectory + currentProcess.ProcessName)); if (sameProcess != null && sameProcess.Length > 0) { //這裡表示是重復的進程 }