0

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?

Elephant
  • 675
  • 1
  • 8
  • 18
  • Are you running VS in administrator mode? Are you running `cmd` in Administrator mode? – Neil Oct 26 '18 at 09:35
  • Have you read about [the restrictions on what processes can successfully set the foreground window](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setforegroundwindow)? Perhaps you're falling foul of one of those restrictions. Does the icon on the taskbar flash when you run the code? If so, that means you *are* being restricted. – Matthew Watson Oct 26 '18 at 09:42
  • @Neil No. I've just tried, it works identically in both modes. – Elephant Oct 26 '18 at 09:49
  • @MatthewWatson The icon on the taskbar does not flashes. – Elephant Oct 26 '18 at 09:50

0 Answers0