没有打开时,就打开一个;如果打开了,再次双击exe后,已打开的窗体就前置;如果窗体已经打开并最小化,就还原窗体并前置!

windowns窗体应用项目:

  1. //以下所有代码放在窗体的Program.cs里面
  2. [DllImport("user32.dll")]
  3. private static extern bool SetForegroundWindow(IntPtr hWnd);
  4. [DllImport("user32.dll")]
  5. private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  6. [DllImport("user32.dll")]
  7. private static extern bool IsIconic(IntPtr hWnd);
  8. private const int SW_RESTORE = 9;
  9. /// <summary>
  10. /// c# 进程窗口显示并前置
  11. /// </summary>
  12. public static void RaiseOtherProcess()
  13. {
  14. Process proc = Process.GetCurrentProcess();
  15. Process.GetProcesses();
  16. foreach (Process otherProc in Process.GetProcessesByName(proc.ProcessName))
  17. {
  18. //ignore "this" process
  19. if (proc.Id != otherProc.Id)
  20. {
  21. // Found a "same named process".
  22. // Assume it is the one we want brought to the foreground.
  23. // Use the Win32 API to bring it to the foreground.
  24. IntPtr hWnd = otherProc.MainWindowHandle;
  25. if (IsIconic(hWnd))
  26. {
  27. ShowWindowAsync(hWnd, 9);
  28. }
  29. SetForegroundWindow(hWnd);
  30. break;
  31. }
  32. }
  33. }
  34. static void Main()
  35. {
  36. Application.EnableVisualStyles();
  37. Application.SetCompatibleTextRenderingDefault(false);
  38. bool createdNew = new bool();
  39. Mutex instance = new Mutex(true, "Regfrm", out createdNew);
  40. if (createdNew)
  41. {
  42. Application.Run(new Regfrm());
  43. instance.ReleaseMutex();
  44. //如果需要窗体重启,并出现问题,将这句改为
  45. //instance.Dispose();
  46. }
  47. else
  48. {
  49. RaiseOtherProcess();
  50. Application.Exit();
  51. }
  52. }

=====================================

windowns窗体应用插件项目:

  1. public Form frm;//这一句放在class里面
  2. private void Button1_Click(object sender, RibbonControlEventArgs e)
  3. {
  4. //以下代码放在插件控件的事件里面
  5. if (frm == null || frm.IsDisposed)
  6. {
  7. frm = new Mainfrm();
  8. frm.Show();
  9. }
  10. else
  11. {
  12. if (frm.WindowState == FormWindowState.Minimized)
  13. {
  14. frm.WindowState = FormWindowState.Normal;
  15. }
  16. frm.Activate();
  17. }
  18. //以上代码放在插件控件的事件里面
  19. }