Setting the Cursor Position in a Win32 Console Application

前端 未结 5 1399
走了就别回头了
走了就别回头了 2020-11-30 08:42

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 m

相关标签:
5条回答
  • 2020-11-30 09:19
    #include <windows.h>
    #include <iostream.h>
    using namespace std;
    int main(int argc, char *argv[])
    {
      int x,y;
      cin>>x>>y;
      SetCursorPos(x,y); //set your co-ordinate
      Sleep(500);
      mouse_event(MOUSEEVENTF_LEFTDOWN,x,y,0,0); // moving cursor leftdown
      mouse_event(MOUSEEVENTF_LEFTUP,x,y,0,0); // moving cursor leftup //for accessing your required co-ordinate
      system("pause");
      return EXIT_SUCCESS;
    }
    
    0 讨论(0)
  • 2020-11-30 09:31

    You were probably using ANSI excape code sequences, which do not work with Windows 32-bit console applications.

    0 讨论(0)
  • 2020-11-30 09:34

    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);
    
    0 讨论(0)
  • 2020-11-30 09:41

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 09:42

    Yeah, you forgot to call SetConsoleActiveScreenBuffer. What exactly was the point of creating your own? Use GetStdHandle(STD_OUTPUT_HANDLE) to get a handle to the existing console.

    0 讨论(0)
提交回复
热议问题