1. using System;
    2. using System.Collections.Generic;
    3. using System.Diagnostics;
    4. using System.Linq;
    5. using System.Runtime.InteropServices;
    6. using System.Threading;
    7. using System.Windows.Forms;
    8. namespace CalendarGenerationTool
    9. {
    10. static class Program
    11. {
    12. [DllImport("user32.dll")]
    13. private static extern bool SetForegroundWindow(IntPtr hWnd);
    14. [DllImport("user32.dll")]
    15. private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
    16. [DllImport("user32.dll")]
    17. private static extern bool IsIconic(IntPtr hWnd);
    18. private const int SW_RESTORE = 9;
    19. /// <summary>
    20. /// c# 进程窗口显示并前置
    21. /// </summary>
    22. public static void RaiseOtherProcess()
    23. {
    24. Process proc = Process.GetCurrentProcess();
    25. Process.GetProcesses();
    26. foreach (Process otherProc in Process.GetProcessesByName(proc.ProcessName))
    27. {
    28. //ignore "this" process
    29. if (proc.Id != otherProc.Id)
    30. {
    31. // Found a "same named process".
    32. // Assume it is the one we want brought to the foreground.
    33. // Use the Win32 API to bring it to the foreground.
    34. IntPtr hWnd = otherProc.MainWindowHandle;
    35. if (IsIconic(hWnd))
    36. {
    37. ShowWindowAsync(hWnd, 9);
    38. }
    39. SetForegroundWindow(hWnd);
    40. break;
    41. }
    42. }
    43. }
    44. /// <summary>
    45. /// 应用程序的主入口点。
    46. /// </summary>
    47. [STAThread]
    48. static void Main()
    49. {
    50. Application.EnableVisualStyles();
    51. Application.SetCompatibleTextRenderingDefault(false);
    52. Mutex instance = new Mutex(true, "MainFrm", out bool createdNew);
    53. if (createdNew)
    54. {
    55. Application.Run(new MainFrm());
    56. instance.ReleaseMutex();
    57. //如果需要窗体重启,并出现问题,将这句改为
    58. //instance.Dispose();
    59. }
    60. else
    61. {
    62. RaiseOtherProcess();
    63. Application.Exit();
    64. }
    65. }
    66. }
    67. }