您的位置:首页 > 其它

关于程序运行一次的三种方法

2005-08-04 20:35 435 查看
经常在网上看到有人问“如何让自己程序只运行一个实例"的问题
我把以前给网友的回答总结一下:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐