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

王朝other·作者佚名  2006-01-10
宽屏版  字体: |||超大  

经常在网上看到有人问“如何让自己程序只运行一个实例"的问题

我把以前给网友的回答总结一下:

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有