如何在c#winform中只打开一个窗口

时间:2014-04-28 05:27:20

标签: c# winforms

我写了ac#windorm应用程序并生成一个安装文件,当我完成安装后,每次双击桌面快捷方式,它都会打开一个新窗口,有没有人可以告诉我怎么才能打开原来的双击桌面上的快捷方式时窗口?

1 个答案:

答案 0 :(得分:3)

我更喜欢类似以下的互斥解决方案。这样,如果应用程序已经加载,它会重新关注应用程序

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

如果应用程序窗口已经运行,它会将焦点放在应用程序窗口上。