12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System;
- using System.Windows.Forms;
- using System.Diagnostics;
- using System.Reflection;
- using System.Runtime.InteropServices;
- namespace SIASUN.TwinCatLogger
- {
- static class Program
- {
- /// <summary>
- /// 应用程序的主入口点。
- /// </summary>
- [STAThread]
- static void Main()
- {
- //Get the running instance.
- Process instance = RunningInstance();
- if (instance == null)
- {
- System.IO.Directory.SetCurrentDirectory(Application.StartupPath);
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new MainForm());
- }
- else
- {
- //There is another instance of this process.
- HandleRunningInstance(instance);
- }
- }
- #region 单实例运行
- public static Process RunningInstance()
- {
- Process current = Process.GetCurrentProcess();
- Process[] processes = Process.GetProcessesByName(current.ProcessName);
- //Loop through the running processes in with the same name
- foreach (Process process in processes)
- {
- //Ignore the current process
- if (process.Id != current.Id)
- {
- //Make sure that the process is running from the exe file.
- if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
- {
- //Return the other process instance.
- return process;
- }
- }
- }
- //No other instance was found, return null.
- return null;
- }
- public static void HandleRunningInstance(Process instance)
- {
- //Make sure the window is not minimized or maximized
- ShowWindowAsync(instance.MainWindowHandle, SW_NORMAL);
- //Set the real intance to foreground window
- SetForegroundWindow(instance.MainWindowHandle);
- }
- [DllImport("User32.dll")]
- private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
- [DllImport("User32.dll")]
- private static extern bool SetForegroundWindow(IntPtr hWnd);
- private const int SW_HIDE = 0;
- private const int SW_NORMAL = 1;
- private const int SW_MAXIMIZE = 3;
- private const int SW_SHOWNOACTIVATE = 4;
- private const int SW_SHOW = 5;
- private const int SW_MINIMIZE = 6;
- private const int SW_RESTORE = 9;
- private const int SW_SHOWDEFAULT = 10;
- #endregion
- }
- }
|