【问题标题】:Activating the main form of a single instance application激活单实例应用程序的主窗体
【发布时间】:2008-09-09 13:35:10
【问题描述】:

在 C# Windows 窗体应用程序中,我想检测该应用程序的另一个实例是否已在运行。 如果是,则激活正在运行的实例的主窗体并退出该实例。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    Scott Hanselman answers 就您的问题详细解答。

    【讨论】:

      【解决方案2】:

      这是我目前在应用程序的 Program.cs 文件中所做的。

      // Sets the window to be foreground
      [DllImport("User32")]
      private static extern int SetForegroundWindow(IntPtr hwnd);
      
      // Activate or minimize a window
      [DllImportAttribute("User32.DLL")]
      private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
      private const int SW_RESTORE = 9;
      
      static void Main()
      {
          try
          {
              // If another instance is already running, activate it and exit
              Process currentProc = Process.GetCurrentProcess();
              foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))
              {
                  if (proc.Id != currentProc.Id)
                  {
                      ShowWindow(proc.MainWindowHandle, SW_RESTORE);
                      SetForegroundWindow(proc.MainWindowHandle);
                      return;   // Exit application
                  }
              }
      
      
              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);
              Application.Run(new MainForm());
          }
          catch (Exception ex)
          {
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用此类检测并在此之后激活您的实例:

                // Detect existing instances
                string processName = Process.GetCurrentProcess().ProcessName;
                Process[] instances = Process.GetProcessesByName(processName);
                if (instances.Length > 1)
                {
                    MessageBox.Show("Only one running instance of application is allowed");
                    Process.GetCurrentProcess().Kill();
                    return;
                }
                // End of detection
        

        【讨论】:

        • 谢谢,我真的很喜欢你的解决方案。
        【解决方案4】:

        Aku,这是一个很好的资源。不久前我回答了一个与此类似的问题。你可以查看我的answer here。即使这是针对 WPF 的,您也可以在 WinForms 中使用相同的逻辑。

        【讨论】:

        • 其实这个技巧我也是从 Sells 书上学来的。但斯科特的文章只是在我的书签中 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        相关资源
        最近更新 更多