Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the Cursor Position in a Win32 Console Application

How can I set the cursor position in a Win32 Console application? Preferably, I would like to avoid making a handle and using the Windows Console Functions. (I spent all morning running down that dark alley; it creates more problems than it solves.) I seem to recall doing this relatively simply when I was in college using stdio, but I can't find any examples of how to do it now. Any thoughts or suggestions would be greatly appreciated. Thanks.

Additional Details

Here is what I am now trying to do:

COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL );
char * str = "Some Text\r\n";
DWDORD len = strlen(str);

SetConsoleCursorPosition(hConsole_c, pos);
WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);
CloseHandle(hConsole_c)

The text string str is never sent to the screen. Is there something else that I should be doing? Thanks.

like image 510
Jim Fell Avatar asked Apr 28 '10 18:04

Jim Fell


People also ask

How do I get console cursor position?

To obtain the position of the cursor, where the next output will be displayed, you can read the Console class's static properties, CursorLeft and CursorTop. These properties return integers that specify the number of characters between the origin of the console and the cursor position.

What is setting cursor position?

When a screen is displayed, the system automatically places the cursor in the first field that is ready for input.


2 Answers

See SetConsoleCursorPosition API

Edit:

Use WriteConsoleOutputCharacter() which takes the handle to your active buffer in console and also lets you set its position.

int x = 5; int y = 6;
COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole_c);
char *str = "Some Text\r\n";
DWORD len = strlen(str);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, str, len, pos, &dwBytesWritten);
CloseHandle(hConsole_c);
like image 96
cpx Avatar answered Sep 28 '22 17:09

cpx


Using the console functions, you'd use SetConsoleCursorPosition. Without them (or at least not using them directly), you could use something like gotoxy in the ncurses library.

Edit: a wrapper for it is pretty trivial:

// Untested, but simple enough it should at least be close to reality...
void gotoxy(int x, int y) { 
    COORD pos = {x, y};
    HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(output, pos);
}
like image 33
Jerry Coffin Avatar answered Sep 28 '22 18:09

Jerry Coffin