【转】winform 程序实现一次只能打开一个该程序

ref: http://www.jb51.net/article/17747.htm

//在程序的main函数中加入以下代码
bool createdNew;
System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out createdNew);
if (createdNew)
{
  Application.Run(new LoginForm());
  instance.ReleaseMutex();
}
else
{
  Application.Exit();
}
//还可以写成以下形式,一个窗体只能启动一次
Form1 a = new Form1();
bool createdNew;
System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out createdNew);
if (createdNew)
{
  a.ShowDialog();
  instance.ReleaseMutex();
}
else
{
  a.Close();
}
private static bool HasRunning()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processCollection = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process p in processCollection)
{
if (p.Id == currentProcess.Id) //检查ID是否相同
{
return true;
}
}
return false;
}
上一篇:转载:mysql如果数据不存在,则插入新数据,否则更新的实现方法


下一篇:POJ 1185 炮兵阵地 状压dp