using System.Diagnostics; using System.Runtime.InteropServices; // Uses to active the exist window [DllImport("User32.dll")] public static extern void SetForegroundWindow(IntPtr hwnd); [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); // 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized private const int WS_SHOWNORMAL = 3; /// <summary> /// 只允一个实例存在 /// </summary> /// <returns></returns> private static bool ExistRunningInstance() { Process currentProcess = Process.GetCurrentProcess(); Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName); foreach (Process proc in procList) { // Found a running instance if (proc.Id != currentProcess.Id) { // Active the running instance ShowWindowAsync(proc.MainWindowHandle, WS_SHOWNORMAL); SetForegroundWindow(proc.MainWindowHandle); return true; } } return false; }