using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { static class Program { [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 INORMAL = 1; /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Process instance = RunningInstance(); if (instance == null) { Application.Run(new Form1()); } else { HandleRunningInstance(instance); } } /// <summary> /// 获取正在运行的实例,没有运行的实例返回null; /// </summary> public static Process RunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); foreach (Process process in processes) { if (process.Id != current.Id) { if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) { return process; } } } return null; } /// <summary> /// 显示已运行的程序。 /// </summary> public static void HandleRunningInstance(Process instance) { ShowWindowAsync(instance.MainWindowHandle, INORMAL);
SetForegroundWindow(instance.MainWindowHandle); } } }
主要用到两个API 函数:
ShowWindowAsync 该函数设置由不同线程产生的窗口的显示状态。
SetForegroundWindow 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。