Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the focus.

Question: How can I give focus back from A.exe to B.exe ?

A -> Focus -> B


Details:
  • Program B is not mine and I can't do anything about it. It has a GUI, multiple windows and 1 of them needs the focus (it might be a modal dialog window).
  • Program A doesn't need any focus and it doesn't interact in any way with program B.
  • Program A starts via Startup shortcut and runs basically in background (it is released but still in development though, that's why console window)
  • I have a few moments/up to minutes to check and give the focus back.
like image 303
Bitterblue Avatar asked Apr 01 '14 08:04

Bitterblue


2 Answers

// 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);
    }
}
like image 153
phcoding Avatar answered Nov 07 '22 02:11

phcoding


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);
}
like image 1
Gabe Halsmer Avatar answered Nov 07 '22 00:11

Gabe Halsmer