C# 项目程序唯一启动(程序运行后,不可以在其他地方再运行这个程序)

bool createNew;
Process process = Process.GetCurrentProcess();
Mutex mutex = new Mutex(true, "CMS IDE", out createNew);
if (!createNew)
{
    foreach (Process p in Process.GetProcessesByName(process.ProcessName))
    {
        //不是同一进程并且本进程启动时间最晚
        if (p.Id != process.Id && (p.StartTime - process.StartTime).TotalMilliseconds <= 0)
        {
            // 确保窗口没有被最小化或最大化
            ShowWindowAsync(p.MainWindowHandle, 4);
            // 设置真实例程为foreground  window
            SetForegroundWindow(p.MainWindowHandle);// 放到最前端

            //关闭当前运行的进程保留之前的进程
            Process.GetCurrentProcess().Kill();//这个地方用kill 而不用Shutdown()的原因是,Shutdown关闭程序在进程管理器里进程的释放有延迟不是马上关闭进程的
            return;
        }
    }
    //若应用程序.exe文件名不一致,提示消息框
    MessageBox.Show("应用程序在其它地方已经运行!", "CMS IDE", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Application.Exit();
    return;
}

写在项目启动的main代码中,这里是写在项目的Program.cs的main函数中

 

 [DllImport("User32.dll")]
 private static extern bool SetForegroundWindow(IntPtr hWnd);
 [DllImport("User32.dll")]
 private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

写在Main外面!

posted @ 2022-07-12 14:19  羽小兮  阅读(270)  评论(0)    收藏  举报