只能同时运行一个实例

来源:互联网 发布:vb自学视频 编辑:程序博客网 时间:2024/05/16 14:42

[STAThread]

static void Main()

{

    
//……

}

是程序运行的入口点,默认情况下,里面的代码大致如下:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(
false);
    Application.Run(
new Form1());
}加入单实例限制后的代码如下:

[STAThread]
static void Main()
{
    
bool isAppRunning = false;
    System.Threading.Mutex mutex 
= new System.Threading.Mutex(
        
true,
        System.Diagnostics.Process.GetCurrentProcess().ProcessName,
        
out isAppRunning);
    
if (!isAppRunning)
    {
        MessageBox.Show(
"本程序已经在运行了,请不要重复运行!");
        Environment.Exit(
1);
    }
    
else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(
false);
        Application.Run(
new Form1());
    }
}

原创粉丝点击