110,538
社区成员
发帖
与我相关
我的任务
分享
[STAThread]
static void Main()
{
Mutex mutex = new Mutex(false, "myForm");
bool Running = !mutex.WaitOne(50, false);
if (Running)
{
mutex.Close();
MessageBox.Show("应用程序已经启动!");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form3());
}
1. API函数的声明
[DllImport("User32.dll")])
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
// 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized
private const int WS_SHOWNORMAL = 3;
2. 查找并激活已经存在的程序(仅应用于进程名相同的程序)
private static bool ExistRunningInstance()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process proc in procList)
{
// Found a running instance
if (proc.Id != currentProcess.Id)
{
// Active the running instance 3
ShowWindowAsync(proc.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(proc.MainWindowHandle);
return true;
}
}
return false;
}
3. 在Main函数入口判断
[STAThread]
static void Main()
{
// Control only one instance with the same process name can run
if (ExistRunningInstance())
{
Environment.Exit(1);
}
}