C ++控制台应用程序始终置顶?

5

不是在寻找以下内容:

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

但是,我正在寻找一种方法,让我的简单C++ 控制台应用程序始终保持在最前面,
只是为了明确 - 我正在寻找一种以编程方式实现此操作的方法:)我努力搜索,但只找到了上述不想要的内容...

那么,在Windows上用C++编写的控制台应用程序有没有一种以编程方式始终保持在最前面的方法呢?

PS:是的,存在一个具有相应标题的问题,但该问题的OP实际上正在寻找其他内容(键盘钩子等) - 因此,那里的答案与我的问题无关。

解决方案:

快速答案 => 参见@AlexanderVX的被接受的答案

示例和说明 => 请参见下面的我的回答


1
如果是针对Windows的,我可以告诉你需要什么。是吗? - Alexander V
3
这很可能是与窗口框架相关的。你能澄清一下你的目标是什么吗?是Windows,X Window,还是其他的? - Angew is no longer proud of SO
@Nit 和其他人 - 什么不清楚?(因为我已经说明了它的目的是用于 Windows,所以这样说更奇怪...) - jave.web
2个回答

11

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

3
你提供的链接描述了一种过于复杂的获取早期Windows版本句柄的方法。在XP及其以后的版本中,你可以直接使用GetConsoleWindow()函数。 - chris
1
同意 GetConsoleWindow 可以改善它。 - Alexander V

5
@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 :(";
}

参考资料:

PS: 我本想将此作为@AlexanderVX答案的编辑发布,但大部分stackoverflow的审查员似乎认为“这次编辑偏离了帖子的原意”...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接