1

I've made a little timer program in c++ and once the timer has run out I want the console window to pop up to the foreground in Windows to display the "finished" message. I read about using "SetForegroundWindow(hwnd)" which does exactly what I want when I run the code from visual studio, but when I build a release and run the exe from outside of VS, the console window doesn't pop up, instead it's icon in the system tray flashes. Any ideas why this might be? I've tested it on 64 bit Windows 7 and 10 and both did the same thing.

Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
tomh1012
  • 274
  • 1
  • 10
  • 1
    https://stackoverflow.com/questions/19136365/win32-setforegroundwindow-not-working-all-the-time – Joe Jan 20 '18 at 01:59
  • Ah! Fab thanks, it was the alt hack on that thread that got it, thank you! – tomh1012 Jan 20 '18 at 02:13
  • Although just as a precaution, do you know if that alt hack can have any adverse effects? Like if it's simulating pressing the alt key, if the user was at that moment also pressing f4, would that act like they had used alt +f4 to close their program or does the alt press only apply to my program? – tomh1012 Jan 20 '18 at 02:15
  • 1
    Possible duplicate of [Win32 ::SetForegroundWindow() not working all the time](https://stackoverflow.com/questions/19136365/win32-setforegroundwindow-not-working-all-the-time) – zett42 Jan 20 '18 at 11:03
  • _"Although just as a precaution, do you know if that alt hack can have any adverse effects?"_ -- Make sure your uninstaller is working fine as this will be the most frequently used function of your program. – zett42 Jan 20 '18 at 11:06
  • Ah... I'll take that as a yes then... – tomh1012 Jan 26 '18 at 18:58

1 Answers1

3

In most cases you can use SetForegroundWindow as long as the window is properly restored. Sometimes the system may refuse the request (see documentation) There is usually a good reason for it and you should not try to override the system. If SetForegroundWindow failed then you still have the backup option where you get that blinking button in the task bar to alert the user.

void show(HWND hwnd)
{
    WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
    GetWindowPlacement(hwnd, &place);
    switch(place.showCmd)
    {
    case SW_SHOWMAXIMIZED:
        ShowWindow(hwnd, SW_SHOWMAXIMIZED);
        break;
    case SW_SHOWMINIMIZED:
        ShowWindow(hwnd, SW_RESTORE);
        break;
    default:
        ShowWindow(hwnd, SW_NORMAL);
        break;
    }
    SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
    SetForegroundWindow(hwnd);
}

int main()
{
    HWND hwnd = GetConsoleWindow();
    ShowWindow(hwnd, SW_SHOWMINIMIZED);
    //Test: manually click another window, to bring that other window on top
    Sleep(5000);

    //this window should restore itself
    show(hwnd);
    system("pause");
    return 0;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77