阻止用户运行多个进程实例

时间:2014-11-10 15:03:02

标签: c# process managementeventwatcher

我不是一位经验丰富的程序员,所以任何建议/指导/示例都将不胜感激!我在C#(.Net framework 4.5)中有一个Windows窗体应用程序正在替换Windows服务(遇到了Session0变量的问题)。应用程序需要打开一个进程,(我将以记事本为例)并每5分钟检查一次记事本是否仍处于打开状态。如果未打开记事本,表单应用程序必须打开它的实例。应用程序必须阻止用户打开另一个记事本实例(如果它已经打开)。我的编码目前关闭所有记事本实例。我只需要应用程序来停止打开第二个记事本实例。问题是根本不允许用户与应用程序交互,因为您将在编码中注意到用户甚至看不到表单。这是我到目前为止的编码:

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ShowInTaskbar = false;
        this.Visible = false;
        //handle Elapsed event
        myTimer.Tick += new EventHandler(OnElapsedTime);
        //This statement is used to set interval to 5 minute (= 300,000 milliseconds)
        myTimer.Interval = 60000;//300000;
        //enabling the timer
        myTimer.Enabled = true;
        WatchForProcessStart("Notepad.exe");
    }

     private void OnElapsedTime(object source, EventArgs e)
    {
        bool status = IsProcessOpen("notepad");
          if (status == true)
          {
              //TraceService("Notepad is already open" + DateTime.Now);
          }
          else
          {
            Process process = new Process();
            process.StartInfo.FileName = "notepad.exe";
            process.EnableRaisingEvents = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.Start();
            //TraceService("Notepad opened" + DateTime.Now);
          }
    }

     public bool IsProcessOpen(string procName)
     {
         System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(procName);
         if (proc.Length > 0)
         {
             return true;
         }
         else
         {
             return false;
         }
     }

     private ManagementEventWatcher WatchForProcessStart(string processName)
     {
         string queryString =
             "SELECT TargetInstance" +
             "  FROM __InstanceCreationEvent " +
             "WITHIN  10 " +
             " WHERE TargetInstance ISA 'Win32_Process' " +
             "   AND TargetInstance.Name = '" + processName + "'";

         // The dot in the scope means use the current machine
         string scope = @"\\.\root\CIMV2";

         // Create a watcher and listen for events
         ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
         watcher.EventArrived += ProcessStarted;
         watcher.Start();
         return watcher;
     }

     private void ProcessStarted(object sender, EventArrivedEventArgs e)
     {
         ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
         string processName = targetInstance.Properties["Name"].Value.ToString();
         bool status = IsProcessOpen("notepad");
         if (status == true)
         {
             System.Diagnostics.Process.Start("cmd.exe", "/c taskkill /IM notepad.exe");
         }
         else
         {
             Process process = new Process();
             process.StartInfo.FileName = "notepad.exe";
             process.EnableRaisingEvents = true;
             process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
             process.Start();
         }
     }

1 个答案:

答案 0 :(得分:1)

将其包裹在Mutex

 var mutexId = "MyApplication";
 using (var mutex = new Mutex(false, mutexId))
 {
    if (!mutex.WaitOne(0, false))
    {
       MessageBox.Show("Only one instance of the application is allowed!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Hand);
       return;
    }
    // Do scome work
 }

如果要将其限制为每台计算机一个实例,则mutexId需要以Global \

为前缀