使程序只能够运行一个

实现:

using System.Threading;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
    public int nLength;
    public int lpSecurityDescriptor;
    public int bInheritHandle;
}

[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int GetLastError();

[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);

[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int ReleaseMutex(IntPtr hMutex);

const int ERROR_ALREADY_EXISTS = 0183;

[STAThread]
static void Main()
{
    IntPtr hMutex;
    hMutex = CreateMutex(null, false, "test");
    if (GetLastError() != ERROR_ALREADY_EXISTS)
    {
        Application.Run(new Form1());
    }
    else
    {
        MessageBox.Show("本程序只允许同时运行一个");
        ReleaseMutex(hMutex);
    }
}
Contributors: FHL