【问题标题】:How to hide console cursor in c?如何在c中隐藏控制台光标?
【发布时间】:2015-07-19 12:38:27
【问题描述】:

我有一个简单的 C 程序,表示控制台中的加载屏幕,但我无法隐藏光标。我尝试提高睡眠功能的速度,以便重置光标计时器并且光标会消失,但这不起作用。

关于如何隐藏光标的任何提示?

代码:

#include <stdio.h>
#include <stdlib.h>

const int TIME = 1;

int main(int argc,char *argv[]){
    int i;
    while (1){
        printf("loading");
        for (i=0;i<3;i++){
            sleep(TIME);
            printf(".");
        }
        sleep(TIME);
        printf("\r");
        system("Cls");
        sleep(TIME);
    }
}

【问题讨论】:

  • 我认为您在 windows/dos 上需要conio.h,而不是system("cls") 等,也许您也应该能够控制光标。在 *nix os 上,有一些控制字符可以做到这一点,我不知道 windows 中的等价物应该是什么。
  • @iharob ,我不知道conio.h 做了什么,也不知道使用它时正确的说法是什么。
  • @AaronCritchley 我看到了那个问题,但我不知道远程终端是什么,即使在阅读了那个问题中的链接问题之后

标签: c windows-console text-cursor


【解决方案1】:

这里有一个适用于 Windows 和 Linux 的解决方案:

#include <iostream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
#endif // _WIN32
using namespace std;

void show_console_cursor(const bool show) {
#if defined(_WIN32)
    static const HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cci;
    GetConsoleCursorInfo(handle, &cci);
    cci.bVisible = show; // show/hide cursor
    SetConsoleCursorInfo(handle, &cci);
#elif defined(__linux__)
    cout << (show ? "\033[?25h" : "\033[?25l"); // show/hide cursor
#endif // Windows/Linux
}

【讨论】:

    【解决方案2】:

    延伸比沙尔的回答:

    隐藏光标: printf("\e[?25l");

    要重新启用光标: printf("\e[?25h");

    Source

    【讨论】:

      【解决方案3】:
      printf("\e[?25l");
      

      这应该工作!它取自 ANSI 代码表,其中的字符不仅仅是它们所看到的。它们的行为类似于某种形式的命令。

      【讨论】:

        【解决方案4】:

        将以下函数添加到您的程序中

        #include <windows.h>
        
        void hidecursor()
        {
           HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
           CONSOLE_CURSOR_INFO info;
           info.dwSize = 100;
           info.bVisible = FALSE;
           SetConsoleCursorInfo(consoleHandle, &info);
        }
        

        并在您的main 中调用它。

        MSDN阅读更多内容

        【讨论】:

        • 启动时光标会稍微闪烁,但效果很酷。有点像你正在启动一个启动时有点麻烦的大程序哈哈。
        猜你喜欢
        • 1970-01-01
        • 2013-11-30
        • 1970-01-01
        • 1970-01-01
        • 2015-01-26
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2010-10-10
        相关资源
        最近更新 更多