我开发了一个C#windows应用程序并创建了它的exe.我想要的是,当我尝试运行应用程序时,如果它已经处于运行状态而不是激活该应用程序,则打开新的应用程序
这意味着我不想多次打开同一个应用程序
Jac*_*nev 11
使用以下代码将焦点设置为当前应用程序:
[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);
}
Run Code Online (Sandbox Code Playgroud)
您可以从 user32.dll 调用 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);
Run Code Online (Sandbox Code Playgroud)
作为参数,您传递要放在前面和焦点的进程的窗口句柄。
SetForegroundWindow(myProcess.MainWindowHandle);
SetFocus(new HandleRef(null, myProcess.Handle)); // not needed
Run Code Online (Sandbox Code Playgroud)
另请参阅msdna 上 SetForegroundWindow Methode 的限制。
使用以下代码部分对 exe 进行多个实例检查,以及在表单加载时是否返回 true。要在您的应用程序中运行此功能,请包含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;
}
Run Code Online (Sandbox Code Playgroud)