因为一个项目的需求,要实现程序只有一个实例运行。在网上搜了很久,最后在CSDN上面看到一回复。得到启示,完成该功能。
主要用的是互斥对象来实现。代码如下:
static class Program
{
[DllImport("coredll.Dll",SetLastError= true)]
private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);
[DllImport("coredll.Dll",SetLastError = true)]
private static extern int ReleaseMutex(IntPtr hMutex);
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public int lpSecurityDescriptor;
public int bInheritHandle;
}
const int ERROR_ALREADY_EXISTS = 0183;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[MTAThread]
static void Main()
{
IntPtr hMutex = CreateMutex(null, false, "StandardWorkMan");
if (Marshal.GetLastWin32Error() != ERROR_ALREADY_EXISTS)
{
Application.Run(new FormWorkList());
}
else
{
MessageBox.Show("已经启动了一个程序,请勿重复打开", "系统提示",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
ReleaseMutex(hMutex);
Application.Exit();
}
}
}
{
[DllImport("coredll.Dll",SetLastError= true)]
private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);
[DllImport("coredll.Dll",SetLastError = true)]
private static extern int ReleaseMutex(IntPtr hMutex);
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public int lpSecurityDescriptor;
public int bInheritHandle;
}
const int ERROR_ALREADY_EXISTS = 0183;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[MTAThread]
static void Main()
{
IntPtr hMutex = CreateMutex(null, false, "StandardWorkMan");
if (Marshal.GetLastWin32Error() != ERROR_ALREADY_EXISTS)
{
Application.Run(new FormWorkList());
}
else
{
MessageBox.Show("已经启动了一个程序,请勿重复打开", "系统提示",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
ReleaseMutex(hMutex);
Application.Exit();
}
}
}
上面代码完全正常,我的问题是大部分自己很早就写出来了。只是问题在下面:
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
我用的是平台调用里面的GetLastError(),结果一直出不来想要的效果。调试时发现无论打开多少个实例,GetLastError()的值一直都是6(INVALID_HANDLE_VALUE)????很不解。 望明白的人说明一下。谢谢。