Tuesday 29 October 2013

Hide/Resize TEXT Cursor

Although I doubt I'll be doing this much longer, right now I'm writing drop-down menus, keyboard navigation menus, highlight/de-highlight selections all in the console window. Suppose the user is going to select one out of three items using the arrow keys. S/He has the options on the screen and one of them is highlighted, but there's a blinking cursor in one part of the screen :(
Although it means nothing because we have deactivated most of the keys on the keyboard, it's distracting.
Also if the user is scrolling through many pages of text, they can see flashes of the cursor as it clears the screen and as the new text is written.

So, how do we hide the cursor?

If we want to hide or re-size the text cursor in the console window, we will have to look at Windows programming.

I've put them in 2 functions. The first function (cursor_hide) hides the cursor, the second one (cursor_show) brings it back.

You will notice that the functions also allow you to change the cursor size. A minimum of 10, which is the old blinking line, to a maximum of 100, which is a blinking box. I used a global variable x. Changing its value changes the cursor size. If you do not foresee having to change the cursor size within the course of your program, just set it directly- like so: ConCurInf.dwSize=10;

Here is the code.


#include <windows.h>
#include <stdio.h>
#include <conio.h>

void cursor(void);
void cursor1(void);
int x=10;

void cursor_hide(void);
void cursor_show(void);

int main()
{
    cursor_hide();
    printf("Cursor Gone\n");
    getch();
    cursor_show();
    printf("Cursor Back\n");
    getch();
    x=100;
    cursor_show();
    printf("Cursor big. (Upto 100)\n");
    getch();
    x=10;
    cursor_show();
    printf("Cursor Small. (Downto 10)\n");
    getch();
    return 0;
}

void cursor_hide(void)
{
    HANDLE hOut;
    CONSOLE_CURSOR_INFO ConCurInf;

    hOut=GetStdHandle(STD_OUTPUT_HANDLE);

    ConCurInf.dwSize=x;
    ConCurInf.bVisible=FALSE;

    SetConsoleCursorInfo(hOut, &ConCurInf);
}

void cursor_show(void)
{
    HANDLE hOut;
    CONSOLE_CURSOR_INFO ConCurInf;
    hOut=GetStdHandle(STD_OUTPUT_HANDLE);

    ConCurInf.dwSize=x;
    ConCurInf.bVisible=TRUE;

    SetConsoleCursorInfo(hOut, &ConCurInf);
}

No comments:

Post a Comment