保证Winform程序只有一个实例在运行

ExpandedBlockStart.gif 代码
using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Threading;
using  System.Windows.Forms;

namespace  Terry{
    
class  Program
    {
        
private  Mutex mutex  =   null ;

        
public  Program()
        {
            mutex 
=   new  Mutex( false " TerrySoft_MUTEX " );
            
if  ( ! mutex.WaitOne( 0 false ))
            {
                mutex.Close();
                mutex 
=   null ;
            }
        }

        
public   void  ReleaseMutex()
        {
            
if  (mutex  !=   null )
            {
                mutex.ReleaseMutex();
                mutex 
=   null ;
            }
        }

        
~ Program()
        {
            ReleaseMutex();
        }

                
///  
        
///  The main entry point for the application.
        
///  

        [STAThread]
        
static   void  Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false );

            Program cm 
=   new  Program();
            
if  (cm.mutex  ==   null )
            {
                MessageBox.Show(
" 已经有一个程序在运行中。 " );
            }
            
else
            {
                Application.Run(
new  frmStart());
            }
            cm.ReleaseMutex();
// 手工释放Mutex

        }

    }
}

 

转载于:https://www.cnblogs.com/zitjubiz/archive/2010/03/31/1701219.html

你可能感兴趣的:(保证Winform程序只有一个实例在运行)