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

时间:2014-11-21 19:14:52

标签: c++ windows console-application always-on-top

正在寻找:

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

我正在寻找一种方法,让我的简单C ++ 控制台应用程序始终保持最佳状态,
只是要明确 - 我正在寻找一种方法如何以编程的方式做到这一点:)我努力寻找但只找到了以上 - 我不想要的......

那么如何在 Windows 的C ++中以编程方式使您的控制台应用始终处于最佳状态?

PS:是的,有一个现有的question with a coresponding title,但该问题的OP实际上正在寻找其他东西(键盘钩子,......) - 所以答案是我的问题的主题。

解决方案:

快速回答 =>请参阅@AlexanderVX的accepted answer

示例&解释 => {/ 3}}下方

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:3)

由于@AlexanderVX's answer显示了一个快速的答案,我还想向您展示我的最终实施,并提供适当的评论来解释什么是:):

不要忘记将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的评论者都认为“这个编辑偏离了帖子的原始意图”......