0

我不是一个经验丰富的程序员,所以任何建议/指导/示例将不胜感激!我在 C#(.Net 框架 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();
         }
     }
4

1 回答 1

1

将其包裹在互斥体中

 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\ 为前缀

于 2014-11-10T15:05:25.820 回答