Program.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Windows.Forms;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. namespace SIASUN.TwinCatLogger
  7. {
  8. static class Program
  9. {
  10. /// <summary>
  11. /// 应用程序的主入口点。
  12. /// </summary>
  13. [STAThread]
  14. static void Main()
  15. {
  16. //Get the running instance.
  17. Process instance = RunningInstance();
  18. if (instance == null)
  19. {
  20. System.IO.Directory.SetCurrentDirectory(Application.StartupPath);
  21. Application.EnableVisualStyles();
  22. Application.SetCompatibleTextRenderingDefault(false);
  23. Application.Run(new MainForm());
  24. }
  25. else
  26. {
  27. //There is another instance of this process.
  28. HandleRunningInstance(instance);
  29. }
  30. }
  31. #region 单实例运行
  32. public static Process RunningInstance()
  33. {
  34. Process current = Process.GetCurrentProcess();
  35. Process[] processes = Process.GetProcessesByName(current.ProcessName);
  36. //Loop through the running processes in with the same name
  37. foreach (Process process in processes)
  38. {
  39. //Ignore the current process
  40. if (process.Id != current.Id)
  41. {
  42. //Make sure that the process is running from the exe file.
  43. if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
  44. {
  45. //Return the other process instance.
  46. return process;
  47. }
  48. }
  49. }
  50. //No other instance was found, return null.
  51. return null;
  52. }
  53. public static void HandleRunningInstance(Process instance)
  54. {
  55. //Make sure the window is not minimized or maximized
  56. ShowWindowAsync(instance.MainWindowHandle, SW_NORMAL);
  57. //Set the real intance to foreground window
  58. SetForegroundWindow(instance.MainWindowHandle);
  59. }
  60. [DllImport("User32.dll")]
  61. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  62. [DllImport("User32.dll")]
  63. private static extern bool SetForegroundWindow(IntPtr hWnd);
  64. private const int SW_HIDE = 0;
  65. private const int SW_NORMAL = 1;
  66. private const int SW_MAXIMIZE = 3;
  67. private const int SW_SHOWNOACTIVATE = 4;
  68. private const int SW_SHOW = 5;
  69. private const int SW_MINIMIZE = 6;
  70. private const int SW_RESTORE = 9;
  71. private const int SW_SHOWDEFAULT = 10;
  72. #endregion
  73. }
  74. }