【转】c# winform 只允许运行一个实例

c# winform 只允许运行一个实例

分类: c# winform 213人阅读 评论(0) 收藏 举报
方法 1:

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Windows.Forms;  
  4. using System.Diagnostics;  
  5. namespace WFForbidAction  
  6. {  
  7.     static class Program  
  8.     {  
  9.         /// <summary>   
  10.         /// 应用程序的主入口点。   
  11.         /// </summary>   
  12.         [STAThread]  
  13.         static void Main()  
  14.         {  
  15.             Application.EnableVisualStyles();  
  16.             Application.SetCompatibleTextRenderingDefault(false);  
  17.             #region 只允许运行一个实例   
  18.             Process pr = Process.GetCurrentProcess();  
  19.             Process[] prlist = Process.GetProcessesByName(pr.ProcessName);  
  20.             if (prlist.Length >= 2)  
  21.             {  
  22.                 return;  
  23.             }  
  24.             #endregion   
  25.             Application.Run(new Form1());  
  26.         }  
  27.     }  
  28. }  
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
namespace WFForbidAction
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            #region 只允许运行一个实例
            Process pr = Process.GetCurrentProcess();
            Process[] prlist = Process.GetProcessesByName(pr.ProcessName);
            if (prlist.Length >= 2)
            {
                return;
            }
            #endregion
            Application.Run(new Form1());
        }
    }
}

 

方法2:

 

  1. bool exist;//定义一个bool变量,用来表示是否已经运行   
  2.             //创建Mutex互斥对象   
  3.             System.Threading.Mutex newMutex = new System.Threading.Mutex(true"test"out exist);  
  4.             if (exist)//如果没有运行   
  5.             {  
  6.                 newMutex.ReleaseMutex();//运行新窗体   
  7.             }  
  8.             else  
  9.             {  
  10.                 MessageBox.Show("本程序一次只能运行一个实例!",  
  11.                                            "温馨提示",  
  12.                                            MessageBoxButtons.OK,  
  13.                                            MessageBoxIcon.Information);  
  14.                 this.Close();  
  15.             }  

 

转自:http://blog.csdn.net/czh4869623/article/details/6881121

posted @ 2013-07-22 09:20  哈哈好玩  阅读(159)  评论(0编辑  收藏  举报