如何在C#中从控制台窗口返回焦点?

Bit*_*lue 5 c# console user-interface winapi focus

我有一个用黑色Windows控制台打开的C#控制台应用程序(A)。有时在启动时,它会从另一个需要焦点的程序(B)中抢走焦点。

问:我怎样才能给从焦点回到A.exeB.exe

A -> Focus -> B
Run Code Online (Sandbox Code Playgroud)


细节:

  • 程序B不是我的,我对此无能为力。它有一个GUI,有多个窗口,其中一个窗口需要焦点(它可能是模式对话框窗口)。
  • 程序A不需要任何关注,也不需要与程序B进行任何交互。
  • 程序A通过启动快捷方式启动,并且基本上在后台运行(虽然已发布但仍在开发中,这就是控制台窗口的原因)
  • 我有几分钟/几分钟的时间来检查并重新确定焦点。

phc*_*ing 5

// this should do the trick....

[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr WindowHandle);

public const int SW_RESTORE = 9;

private void FocusProcess(string procName)
{
    Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName);
    if (objProcesses.Length > 0)
    {
        IntPtr hWnd = IntPtr.Zero;
        hWnd = objProcesses[0].MainWindowHandle;
        ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
        SetForegroundWindow(objProcesses[0].MainWindowHandle);
    }
}
Run Code Online (Sandbox Code Playgroud)