简体   繁体   English

C ++将控制台窗口置于最前面

[英]C++ bring console window to the front

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. 我用c ++编写了一个小计时器程序,一旦计时器用完,我希望控制台窗口在Windows中弹出到前台以显示“完成”消息。 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. 我读到有关使用“ SetForegroundWindow(hwnd)”的信息,该功能正是我从Visual Studio运行代码时想要的,但是当我构建发行版并从VS外部运行exe时,不会弹出控制台窗口,而是它在系统任务栏中的图标闪烁。 Any ideas why this might be? 任何想法为什么会这样? I've tested it on 64 bit Windows 7 and 10 and both did the same thing. 我已经在64位Windows 7和10上对其进行了测试,并且都做了相同的事情。

In most cases you can use SetForegroundWindow as long as the window is properly restored. 在大多数情况下,只要正确还原窗口,就可以使用SetForegroundWindow 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. 如果SetForegroundWindow失败,则您仍然可以使用备份选项,在该选项中,任务栏中的闪烁按钮将向用户发出警报。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM