c++ - 当我单击控制台时,光标再次出现。我怎样才能防止这种情况?

我还是新手。所以我基本上是在一个视觉工作室项目上。称为控制台应用程序的东西。

#include <windows.h>
#include <iostream>

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coords;
void setcursor(bool visible, DWORD size) { //if we set it to (0,0) in main. the cursor won't be there anymore. the size becomes 20, and it no longer becomes visible? that's the gist of it.
    CONSOLE_CURSOR_INFO lpCursor;
    if (size == 0) size = 20; //makes the cursor bigger so it won't show?
    lpCursor.bVisible = visible;
    lpCursor.dwSize = size;
    SetConsoleCursorInfo(console, &lpCursor);
}
void gotoxy(int x, int y) { //to change the coordinates the text outputs to on the cmd
    coords.X = x;
    coords.Y = y;
    SetConsoleCursorPosition(console, coords);
}

下面这个东西(方法?)称为“setcursor”。在我使 cmd 屏幕变大之后,甚至在我之后再次最小化它之后。它停止工作。光标的东西再次出现,就好像我从未设置过该方法一样。我如何使光标永远消失。

int main()
{
    gotoxy(4, 4);
    setcursor(0, 0); //makes that cursor on the console that awaits your text input go invisible or something.
    int x;
    std::cin >> x;
    std::cout << x;
}

回答1

当您调整或最小化/恢复命令窗口时,命令窗口中的光标将重新显示。您需要在每次窗口形状更改时调用此函数 setcursor(...) 以使其再次不可见。

SetConsolCursorInfo 函数将拒绝光标大小为 0。这就是你测试它的原因,并在这一行中阻止它 if (size == 0) size = 20;

回答2

基于 JimmyNJ 的回答。我想我需要一种方法来检测窗口大小的变化,因为 void thinge 会自行重置回 0。所以我继续搜索有关堆栈溢出的问题。https://stackoverflow.com/questions/60983871/how-do-i-disable-or-detect-mode-changes-in-windows-console

我尝试了上面问题中给出的答案。它检测窗口缓冲区大小的变化(我不知道这意味着什么),也许是屏幕分辨率?

在 main() 上面声明这个

HWND g_hWindow = GetConsoleWindow();
void CALLBACK EventProc(HWINEVENTHOOK hook, DWORD event, HWND wnd, LONG object, LONG child, DWORD thread, DWORD time) {
    setcursor(0, 0);
}

并在 main() 内部写下:

HWINEVENTHOOK eventHook = SetWinEventHook(EVENT_CONSOLE_LAYOUT, EVENT_CONSOLE_LAYOUT, NULL, EventProc, 0, 0, WINEVENT_OUTOFCONTEXT);
if (eventHook != 0) {
            setcursor(0, 0);
        }

请注意,在我正在制作的控制台游戏中,我在 do-while 循环中有那个“if”。这也不能正确解决问题。同样,那个 void thinge 喜欢将自己重置为零。但是当它发生时,这会修复它。

相似文章

随机推荐

最新文章