要判断我运行的这个程序是否已经启动了。第一次启动程序是允许的,但是如果程序已经启动了,就不允许程序启动了在showform 中就不允许加载。我写了一段代码:
Process[] mProcs = Process.GetProcesses();
int iCount = 0;
foreach(Process sProc in mProcs)
{
if(sProc.ProcessName=="WindowsApplication11")
{
iCount++;
}
if(iCount==2)
{
sProc.Kill();
}
}
这样一来,就杀死了第一个启动的程序,有什么好的解决办法吗?

解决方案 »

  1.   

    [STAThread]
            static void Main(string[] args)
            {
                //保证该程序只有一个在运行
                bool createdNew;
                System.Threading.Mutex mutex_Application = new System.Threading.Mutex(true,"test",out createdNew);
                if (!createdNew)
                {
                    MessageBox.Show("本程序只允许同时运行一个!");
                    return;
                }
           
                Application.Run();
               
            }   
    还是用进程吧,我的程序中试用。private void MainWindow_Load(object sender, System.EventArgs e)
    {    Process[] processes=Process.GetProcessesByName("MYEXENAME");
          if( processes != null)
         {
        if( (processes.Length)== 2)  //第2个进程
        {
           processes[1].CloseMainWindow();      }
       }
    }