C++控制台应用程序始终位于顶部

C++ console application always on top?

本文关键字:于顶部 控制台 应用程序 C++      更新时间:2023-10-16

我不是在找

  • 使另一个窗口始终位于顶部
  • 制作任何类型的GUI - 对话框等... 在顶部

但是,我正在寻找一种方法,如何使我的简单C++控制台应用程序始终保持领先地位,
只是为了清楚 - 我正在寻找一种如何以编程方式执行此操作的方法:)我努力搜索,但只找到了上述内容 - 我不想要的......

那么有没有办法让你的控制台应用在 Windows 上的C++中以编程方式始终位于顶部?

PS:是的,有一个具有相应标题的现有问题,但该问题的OP实际上正在寻找其他东西(键盘钩子,...) - 所以答案与我的问题无关。

溶液:

快速回答=>查看接受的答案@AlexanderVX

示例和解释=>我在下面的答案

OP 帖子中的链接指的是 Windows。

首先,需要获取控制台窗口的句柄:https://support.microsoft.com/kb/124103

或者更好和现代:获取控制台句柄的GetConsoleWindow方式。

然后你需要做一个非常简单的技巧:

::SetWindowPos(hwndMyWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
::ShowWindow(hwndMyWnd, SW_NORMAL);

由于@AlexanderVX的回答显示了一个快速答案,我还想向您展示我的最终实现,并附上适当的注释,解释:)做什么:

不要忘记将Windows版本设置为等于或大于0x0500并包含windows.h库:

#define _WIN32_WINNT 0x0500
#include <windows.h>

我已经把小应用程序的例子放在了:http://ideone.com/CeLQj3

示例及说明:

// GetConsoleWindow() => returns:
// "handle to the window used by the console
// associated with the calling process
// or NULL
// if there is no such associated console."
HWND consoleWindowHandle = GetConsoleWindow();
if( consoleWindowHandle ){
    cout << endl << "Setting up associated console window ON TOP !";
    SetWindowPos(
        consoleWindowHandle, // window handle
        HWND_TOPMOST, // "handle to the window to precede
                      // the positioned window in the Z order
                      // OR one of the following:"
                      // HWND_BOTTOM or HWND_NOTOPMOST or HWND_TOP or HWND_TOPMOST
        0, 0, // X, Y position of the window (in client coordinates)
        0, 0, // cx, cy => width & height of the window in pixels
        SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW // The window sizing and positioning flags.
    );
    // OPTIONAL ! - SET WINDOW'S "SHOW STATE"
    ShowWindow(
        consoleWindowHandle, // window handle
        SW_NORMAL // how the window is to be shown
                  // SW_NORMAL => "Activates and displays a window.
                  // If the window is minimized or maximized,
                  // the system restores it to its original size and position.
                  // An application should specify this flag
                  // when displaying the window for the first time."
    );
    cout << endl << "Done.";
} else {
    cout << endl << "There is no console window associated with this app :(";
}

引用:

  • 获取控制台窗口 =>http://msdn.microsoft.com/en-us/library/windows/desktop/ms683175%28v=vs.85%29.aspx
  • 设置窗口位置 =>http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545(v=vs.85).aspx
  • 显示窗口 =>http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
  • 设置 WINVER 或 _WIN32_WINNT =>http://msdn.microsoft.com/en-us/library/windows/desktop/aa383745(v=vs.85).aspx#setting_winver_or__win32_winnt

PS:我想把它作为@AlexanderVX答案的编辑发布,但大多数 stackoverflow 的审稿人不知何故认为"这个编辑偏离了帖子的初衷"......