众所周知,控制台缓冲区大小是像二维数组一样组成的。我正在尝试实现 on click buttons
(绘制的按钮不是子窗口)但我有一个准确性问题。
因为 Console Window
是可移动和可调整大小的,我必须采取 Mouse Cursor
相对于 Console Window
的位置左上角(我找到了一种以像素为单位准确做到这一点的方法)。但现在问题来了。当我试图找出哪个 character square
Mouse Cursor
打开时,它会变得不准确(大约 3 ~ 5 个像素的错误),这是实现 on click buttons
时的问题。
这些是我使用的功能。另请记住,我们之前需要有 GetCurrentConsoleFont()
宣布。 (找到它here)
为了便于测试,我在主程序中实现了一个“画我的东西”小游戏(see full code)。
/** This returns the cursor position relative to any window (not just the console).*/
POINT GetCursPosRelWin(HWND hWindow)
{
POINT rCoord;
RECT windowCoord;
HWND hConsole = GetConsoleWindow();
GetWindowRect(hConsole,&windowCoord);
POINT ptCursor;
GetCursorPos(&ptCursor);
rCoord.x = ptCursor.x - windowCoord.left;
rCoord.y = ptCursor.y - windowCoord.top;
return rCoord;
}
WORD GetCurrentFontHeight()
{
CONSOLE_FONT_INFO cfi;
GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);
return cfi.dwFontSize.Y;
}
WORD GetCurrentFontWidth()
{
CONSOLE_FONT_INFO cfi;
GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);
return cfi.dwFontSize.X;
}
那么,有没有办法让这个方法更加准确呢?
编辑:这是我设法找到的最准确的方法,尽管它仍然不是很精确。
/** See the full code for a better understanding */
/** In the main function as parameters of MoveConsoleCursor() */
MoveConsoleCursor(
(SHORT)((double)(ptCursor.x/GetCurrentFontWidth() - ((ptCursor.x/GetCurrentFontWidth())%10)/10 )),
(SHORT)((double)(ptCursor.y/GetCurrentFontHeight() - 0.5))
);
最佳答案
您可以将 GetCursPosRelWin
更改为:
POINT GetCursPosRelWin(HWND hWindow)
{
POINT ptCursor;
GetCursorPos(&ptCursor);
ScreenToClient(hWindow, &ptCursor);
return ptCursor;
}
和 MoveConsoleCursor
调用:
MoveConsoleCursor(ptCursor.x / GetCurrentFontWidth(), ptCursor.y / GetCurrentFontHeight());
如果滚动条不移动,这会将光标置于正方形的中心。否则,您必须考虑滚动条偏移。
关于c++ - 确定鼠标光标所在的控制台上的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50381934/