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

后端 未结 2 476
我寻月下人不归
我寻月下人不归 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

    To do this for your current running C# Console app...

    [DllImport("user32.dll")]
    public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
    public const int SW_RESTORE = 9;
    static void FocusMe()
    {
        string originalTitle = Console.Title;
        string uniqueTitle = Guid.NewGuid().ToString();
        Console.Title = uniqueTitle;
        Thread.Sleep(50);
        IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
    
        Console.Title = originalTitle;
    
        ShowWindowAsync(new HandleRef(null, handle), SW_RESTORE);
        SetForegroundWindow(handle);
    }
    

提交回复
热议问题