版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
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);