C# WINFORM判断程序已经运行,切只能运行一个实例

判断程序是否已经运行,使程序只能运行一个实例:

方法1:

//这种检测进程的名的方法,并不绝对有效。因为打开第一个实例后,将运行文件改名后,还是可以运行第二个实例.

private static bool isAlreadyRunning()
{
bool b = false;
Process[] mProcs = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
if (mProcs.Length > 1) {
b = true;
}
return b;
}

方法2:

//线程互斥

static void Main()
{
bool canCreateNew;
Mutex m = new Mutex(true, "DRM", out canCreateNew);
if (canCreateNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DRM());
m.ReleaseMutex();
}
else {
MessageBox.Show("程序已经运行!");
}

}

posted @ 2024-02-12 13:39  354993  阅读(87)  评论(0)    收藏  举报