如何将焦点设置为已经处于运行状态的应用程序?

我开发了一个C#windows应用程序并创建了它的exe。 我想要的是,当我尝试运行应用程序时,如果它已经处于运行状态而不是激活该应用程序,则打开新的应用程序

这意味着我不想多次打开同一个应用程序

使用以下代码将焦点设置为当前应用程序:

[DllImport("user32.dll")] internal static extern IntPtr SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); ... Process currentProcess = Process.GetCurrentProcess(); IntPtr hWnd = currentProcess.MainWindowHandle; if (hWnd != IntPtr.Zero) { SetForegroundWindow(hWnd); ShowWindow(hWnd, User32.SW_MAXIMIZE); } 

您可以从user32.dll PInvoke SetForegroundWindow()和SetFocus()来执行此操作。

 [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); // SetFocus will just focus the keyboard on your application, but not bring your process to front. // You don't need it here, SetForegroundWindow does the same. // Just for documentation. [DllImport("user32.dll")] static extern IntPtr SetFocus(HandleRef hWnd); 

作为参数,您传递要引入前端和焦点的过程的窗口句柄。

 SetForegroundWindow(myProcess.MainWindowHandle); SetFocus(new HandleRef(null, myProcess.Handle)); // not needed 

另请参阅msdna上SetForegroundWindow Methode的限制 。

使用Mutex启动应用程序的单个实例。 此外,您可以使用Process类在其上查找您的应用程序和SetFocus。 这里http://social.msdn.microsoft.com/Forums/da-DK/csharpgeneral/thread/7fd8e358-9709-47f2-9aeb-6c35c7521dc3

使用以下代码部分进行exe的多个实例检查,以及它在表单加载时的真实返回。 要在您的应用中运行此function,请using System.Diagnostics; 命名空间

 private bool CheckMultipleInstanceofApp() { bool check = false; Process[] prc = null; string ModName, ProcName; ModName = Process.GetCurrentProcess().MainModule.ModuleName; ProcName = System.IO.Path.GetFileNameWithoutExtension(ModName); prc = Process.GetProcessesByName(ProcName); if (prc.Length > 1) { MessageBox.Show("There is an Instance of this Application running"); check = true; System.Environment.Exit(0); } return check; }