How To Give Back Focus From Console Window in C#?

后端 未结 2 482
我寻月下人不归
我寻月下人不归 2021-01-13 05:49

I have a C# console application (A) that opens with the black windows console. Sometimes at startup it steals the focus from another program (B) that needs

2条回答
  •  遥遥无期
    2021-01-13 06:16

    // 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);
        }
    }
    

提交回复
热议问题