讓程序只運行一個實例的方法一:
static void Main()
{
System.Threading.Mutex mutex;
bool isNew;
mutex = new System.Threading.Mutex(true, "myproject", out isNew);
if (isNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
MessageBox.Show("本程序已經在運行!","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
讓程序只運行一個實例的方法二(會顯示正在運行的窗口):
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
HandleRunningInstance(instance);
}
}
//返回正在運行的程序進程
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/ ", "\\ ") == current.MainModule.FileName)
{
return process;
}
}
}
return null;//第一次運行,返回null
}
//顯示正在運行的進程當前窗口
public static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //置窗口為正常狀態
SetForegroundWindow(instance.MainWindowHandle);
}
#region 調用系統api
[DllImport("User32.dll ")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll ")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
#endregion