我们只想在任何时候运行一个应用程序实例.所以在启动时它会查看应用程序是否正在运行,如果是,它会在主窗口上调用SetForegroundWindow.
这一切都很好...... 大部分时间......
当我们的应用程序启动时,它将显示启动画面和登录表单.这两种形式都有ShowInTaskBar = false.
因此,如果您在显示登录表单时尝试启动该应用程序的另一个副本,则该登录表单不会显示在前面!
特别是当用户也无法在任务栏中看到任何内容时,他们认为所有应用程序都是duff并且无法启动.没有迹象表明还有另一个实例在运行.
有没有解决这个问题的方法?
Nay*_*yan 52
嗯,代码在这里.即使它ShowInTaskBar是false,你应该能够把它带到前面.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public static void bringToFront(string title) {
// Get a handle to the Calculator application.
IntPtr handle = FindWindow(null, title);
// Verify that Calculator is a running process.
if (handle == IntPtr.Zero) {
return;
}
// Make Calculator the foreground application
SetForegroundWindow(handle);
}
Run Code Online (Sandbox Code Playgroud)
注意:您应该FindWindow使用表单的类而不是名称,因为启动屏幕表单有时没有标题甚至控件箱.使用Spy ++深入挖掘.
FindWindow在飞溅中使用.我认为这就是你想要做的事情 - 在加载主表单时将闪屏放在前面.
Sup*_*nus 32
我认为这是更好的解决方案,因为它从最小化状态恢复:
public static class WindowHelper
{
public static void BringProcessToFront(Process process)
{
IntPtr handle = process.MainWindowHandle;
if (IsIconic(handle))
{
ShowWindow(handle, SW_RESTORE);
}
SetForegroundWindow(handle);
}
const int SW_RESTORE = 9;
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);
}
Run Code Online (Sandbox Code Playgroud)
简单的电话:
WindowHelper.BringProcessToFront(process);
Run Code Online (Sandbox Code Playgroud)