简体   繁体   English

如何在c中隐藏控制台光标?

[英]How to hide console cursor in c?

I have a simple C program that represents a loading screen within the console but I can't get the cursor to hide.我有一个简单的 C 程序,它代表控制台中的加载屏幕,但我无法隐藏光标。 I tried cranking up the speed of the sleep function so that the cursor timer would be reset and the cursor would be gone but that doesn't work.我尝试提高睡眠功能的速度,以便重置光标计时器并且光标消失,但这不起作用。

Any tips on how to hide the cursor.有关如何隐藏光标的任何提示。

Code:代码:

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

To extend on Bishal's answer:扩展比沙尔的回答:

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

To re-enable the cursor: printf("\\e[?25h");重新启用光标: printf("\\e[?25h");

Source来源

Add to your program the following function将以下功能添加到您的程序中

#include <windows.h>

void hidecursor()
{
   HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
   CONSOLE_CURSOR_INFO info;
   info.dwSize = 100;
   info.bVisible = FALSE;
   SetConsoleCursorInfo(consoleHandle, &info);
}

and call it in your main .并在您的main调用它。

And read more in the MSDN并在MSDN 中阅读更多内容

printf("\e[?25l");

This should work !这应该有效! It is taken from ANSI codesheet where the characters are not just what they are seen.它取自 ANSI 代码表,其中的字符不仅仅是它们所看到的。 They act like some form of commands.它们就像某种形式的命令。

Here a solution that works both in Windows and Linux:这是一个适用于 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM