c++ - 确定鼠标光标所在的控制台上的角色
问题描述
众所周知,控制台缓冲区大小是由一个二维数组组成的。我正在尝试实现on click buttons
(绘制的按钮不是子窗口),但我遇到了准确性问题。
因为Console Window
是可移动和可调整大小的,所以我必须采用Mouse Cursor
相对于Console Window
左上角的位置(我找到了一种以像素为单位准确执行此操作的方法)。但是现在问题来了。当我试图找出哪个character square
是Mouse Cursor
on 时,它变得不准确(大约 3 ~ 5 个像素的错误),这是实施时的一个问题on click buttons
。
这些是我使用的功能。还要记住,我们需要事先GetCurrentConsoleFont()
声明。(在这里找到)
为了便于测试,我在主体中实现了一个小“画我的东西”游戏(参见完整代码)。
/** 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());
如果滚动条没有移动,这会将光标放在正方形的中心。否则,您必须考虑滚动条偏移量。
推荐阅读
- python - Python:运行长度编码?
- swift - @State 更改时 SwiftUI 视图不更新
- python - 在 Python 中构建质数可迭代对象
- vue.js - Vue 应用企业版:如何为开源软件项目管理干净的代码库
- python - 如何避免 Delaunay.find_simplex 函数返回 -1
- c# - .NET Core - Novell LDAP/AD - 组搜索他所属的用户 - 有人让它工作吗?
- angular - 此条件将始终返回 'false',因为类型 'number' 和 'string' 没有重叠 ngIf
- apache - XAMPP Apache 服务器为 REST API 发出不需要的 301 重定向
- django - 如何在使用夹具的 Django TestCase 中禁用信号?
- reactjs - 优化超过 50 列的 React-Table 渲染?