经常在网上看到有人问“如何让自己程序只运行一个实例"的问题
我把以前给网友的回答总结一下:
1。
#region Mutex对象
Mutex mt=new Mutex(true,"MutexInstance");
if(mt.WaitOne(0,false))
Application.Run(new runonce());
else
MessageBox.Show("您的程序已经在运行了,不能运行两个实例!");
#endregion
2。
#region Process方法
Int32 _isProcessRunning;
_isProcessRunning = System.Diagnostics.Process.GetProcessesByName(
System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length;
if(_isProcessRunning != 1)
{
MessageBox.Show("您的程序已经在运行了,不能运行两个实例!");
}
else
Application.Run(new runonce());
#endregion
3。
[DllImport("kernel32")]
private static extern int GetLastError();
[DllImport("kernel32")]
private static extern int ReleaseMutex(IntPtr hMutex);
[DllImport("kernel32")]
private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes,bool bInitialOwner,string lpName);
[StructLayout( LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public int lpSecurityDescriptor;
public int bInheritHandle;
}
const int ERROR_ALREADY_EXISTS = 0183;
//-------------------------------------------------------------------------
#region Api_Call CreateMutex
IntPtr hMutex;
hMutex=CreateMutex(null,false,"MutexInstance");
if (GetLastError()!=ERROR_ALREADY_EXISTS)
{
Application.Run(new runonce());
}
else
{
MessageBox.Show("本程序只允许同时运行一个");
ReleaseMutex(hMutex);
}
#endregion