5

不是在寻找:

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

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

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

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

解决方案:

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

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

4

2 回答 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);
于 2014-11-21T19:26:28.587 回答
4

正如@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 的评论者都认为“此编辑偏离了帖子的初衷”......

于 2014-11-22T11:04:12.883 回答