我刚刚用 c 语言编写了河内塔的代码,我想使用字符以图形模式显示解决方案。
我想使用 windows.h 和
SetConsoleCursorPosition
函数在控制台中移动光标。
您能帮我告诉我这个功能是否有效以及如何使用它吗?请举一些例子。
这里有一个如何调用
SetConsoleCursorPosition
函数的示例,摘自 cplusplus:
void GoToXY(int column, int line)
{
// Create a COORD structure and fill in its members.
// This specifies the new position of the cursor that we will set.
COORD coord;
coord.X = column;
coord.Y = line;
// Obtain a handle to the console screen buffer.
// (You're just using the standard console, so you can use STD_OUTPUT_HANDLE
// in conjunction with the GetStdHandle() to retrieve the handle.)
// Note that because it is a standard handle, we don't need to close it.
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// Finally, call the SetConsoleCursorPosition function.
if (!SetConsoleCursorPosition(hConsole, coord))
{
// Uh-oh! The function call failed, so you need to handle the error.
// You can call GetLastError() to get a more specific error code.
// ...
}
}
您还可以通过查看SDK文档来了解如何使用Win32函数。谷歌搜索该函数的名称通常会显示相应的文档页面作为第一个命中。
对于
SetConsoleCursorPosition
,页面是 here,对于 GetStdHandle
,页面是 here。
include <Windows.h>
HANDLE desc = GetStdHandle(STD_OUTPUT_HANDLE);//getting the console handle
void ConsoleCursor(bool show, short size) {
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(desc, &CursorInfo);
CursorInfo.bVisible = show;
CursorInfo.dwSize = size;
SetConsoleCursorInfo(desc, &CursorInfo);
}
void CurPos(short x, short y) {
SetConsoleCursorPosition(desc, { x, y });
/*
similarly:
COORD pos ;
pos.X = 50 ;
pos.Y = 12 ;
SetConsoleCursorPosition(desc, pos);
*/
}