SetForegroundWindow() does not work from existing console window

366 Views Asked by At

Following code works only when I run a new instance of console window. For example it works when I run the code from VS or when I double click exe file. However it does not work when I run the exe from already opened CMD.

/// <summary>
/// Activates and displays the window. If the window is minimized or 
/// maximized, the system restores it to its original size and position.
/// </summary>
private const int SW_RESTORE = 9;

[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);

public static void BringToFront(IntPtr handle)
{
    if (IsIconic(handle))
    {
        ShowWindow(handle, SW_RESTORE);
    }

    SetForegroundWindow(handle);
}

Is there any way to make it work, or is it impossible?

0

There are 0 best solutions below