how to position the cursor on the screen?

2019-07-09 00:39发布

问题:

I'm new in programming and currently learning about arrays in C. I'm making a puzzle that contains 15 numbered square pieces mounted on a frame and one piece is empty.It allow the user to hit any of the arrow keys(up,down,left,right).The user will continue hitting the arrow keys till the numbers aren't arranged in ascending order.These pieces can be move horizontally and vertically. My problem is that i don't know how to position the cursor.I know a library function gotoxy() but i think it was used in Turbo C/C++.I'm using Code Blocks.I searched this on Google but couldn't get the result.And yes i'm talking about the keyboard cursor and using window OS.Please help! :)

回答1:

In the old days, MS/DOS used a special driver ANSI.SYS to emulate ANSI command codes. It looks like this good old driver is usable under Windows XP (but you need do configure it in config.sys), but I found some articles saying it no longer works on Windows 7 and above.

So ANSI (or vt100 or vt220) codes are useful in Linux or Unix terminals, but under Windows, my advice would be to directly use the Windows API Console functions declared in Wincon.h - but you should alway include Windows.h when using Windows API functions.

You will need to use the Windows SDK as a reference, but here is a small program writing foo_bar in position 15,5 :

#include <windows.h>
#include <tchar.h> // compatibility 8/16 bits characters

int _tmain(int argc, const LPSTR *argv) {
    HANDLE hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE); // console output handle
    COORD dwCursorPosition;
    DWORD nb;
    dwCursorPosition.X = 15;
    dwCursorPosition.Y = 5;
    ::WriteConsoleOutputCharacter(hStdOut, _T("foo_bar"), 7, dwCursorPosition, &nb);

    return 0;
}

References : Console Reference on MSDN