Set console cursor position in Windows and Linux


In console mode the typical need for set cursor position would be to "update" data in the same fixed position creating a refresh effect. This requirement need to set the cursor in the same point every time and start print characters. Each new print will overwrite the old data and this will create the dynamic update effect.


Follow a ready made function for the the cursor position in console mode.

Code for Windows

void SetCursorPos(int XPos, int YPos)
{
 COORD Coord;

 Coord.X = XPos;
 Coord.Y = YPos;

 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Coord);
}

Code for Linux (please note this code will work in ANSI compatible terminal only)

void SetCursorPos(int XPos, int YPos)
{
 printf("\033[%d;%dH", YPos+1, XPos+1);
}

Comments

  1. Can you show some example program how to use it in windows !!

    ReplyDelete
  2. What kind of additional example do you need? There is a ready-made function to copy and past inside your code. In your console based application just call "SetCursorPos()" with the coordinates you want to move the cursor to (that, obviously, have to be in the console mode range 80x25)

    ReplyDelete
  3. Is there a way to do this in linux using iostream or just with cstdio?

    ReplyDelete
  4. You need to include the Windows.h header for Windows version

    ReplyDelete

Post a Comment

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model