Solved: Setting Cursor Position in Win32 Console App

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

pcpro17

Thread Starter
Joined
Oct 9, 2006
Messages
469
How can I set the cursor position in a Win32 Console application? Here is what I am trying to do:

Code:
    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.
 

IMM

Joined
Feb 1, 2002
Messages
3,257
This is crude but will work - note the comment about a keypress or breakpoint - if the program runs as far as the handle close - you will see nothing.

Code:
#include <windows.h>

int main()
{
  BOOL bSuccess;
  DWORD dwBytesWritten;
  COORD posn;
  char * str = "Some Text\r\n";

  DWORD len = strlen(str);
  HANDLE  hConsole_c = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                                         NULL,
                                         CONSOLE_TEXTMODE_BUFFER,
                                         NULL);
  bSuccess = SetConsoleActiveScreenBuffer(hConsole_c);
  posn.X = 0; posn.Y = 0;
  bSuccess = SetConsoleCursorPosition(hConsole_c, posn);
  bSuccess = WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);
  posn.X = 10; posn.Y = 10;
  bSuccess = SetConsoleCursorPosition(hConsole_c, posn);
  bSuccess = WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);

// if you want to see anything put a keypress or breakpoint here
  CloseHandle(hConsole_c);
return 0;
}
 

pcpro17

Thread Starter
Joined
Oct 9, 2006
Messages
469
Thanks for the tips! I ended up using `GetStdHandle(STD_OUTPUT_HANDLE)` to get the handle to the existing console and `WriteConsoleOutputCharacter()` to write the characters.
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Members online

Top