我用c ++编写了一个小计时器程序,一旦计时器用完,我希望控制台窗口弹出到Windows的前台,以显示"完成"信息。我读到了使用" SetForegroundWindow(hwnd)"当我从visual studio运行代码时,它正是我想要的,但是当我构建一个版本并从VS外部运行exe时,控制台窗口不会弹出,而是在它的图标中系统托盘闪烁。任何想法为什么会这样?我已经在64位Windows 7和10上测试了它,两者都做了同样的事情。
答案 0 :(得分:1)
在大多数情况下,只要窗口正确恢复,您就可以使用SetForegroundWindow
。有时系统可能会拒绝请求( see documentation )通常有充分的理由,您不应该尝试覆盖系统。如果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;
}