著作權聲明:轉載時請以超連結形式標明文章原始出處和作者資訊及本聲明
http://greenlandy.blogbus.com/logs/14388828.html
Code Snippet
- [STAThread]
- private static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- var wb = new Form1();
- Process current = Process.GetCurrentProcess();
- bool newinstance = true;
- Process[] processes = Process.GetProcessesByName(current.ProcessName);
-
- //?曆正在有相同名字??的常式
- foreach (Process process in processes)
- {
- //忽略現有的常式
- if (process.Id != current.Id)
- {
- //確保常式從EXE檔案??
- if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
- {
- //?回另一個常式執行個體
- current = process;
- newinstance = false;
- break;
- }
- }
- }
- if (newinstance)
- {
- Application.Run(wb);
- }
- else
- {
- ShowWindowAsync(current.MainWindowHandle, 1);
-
- //?置真執行個體程為foreground window
- SetForegroundWindow(current.MainWindowHandle);
- }
- }
引入這兩個API函數
Code Snippet
- [DllImport("User32.dll")]
- private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
-
- [DllImport("User32.dll")]
- private static extern bool SetForegroundWindow(IntPtr hWnd);