C++ 如何确定鼠标光标所在的控制台字符?
当字体大小非常小时,我无法将鼠标屏幕坐标转换为控制台2D缓冲区。我找到的唯一方法是:C++ 如何确定鼠标光标所在的控制台字符?,c++,windows,winapi,console,cursor,C++,Windows,Winapi,Console,Cursor,当字体大小非常小时,我无法将鼠标屏幕坐标转换为控制台2D缓冲区。我找到的唯一方法是: COORD CursorToBuffer() { POINT ptCursor; GetCursorPos(&ptCursor); ScreenToClient(GetConsoleWindow(), &ptCursor); /** Now ptCursor has the Mouse Position relative to the console client
COORD CursorToBuffer()
{
POINT ptCursor;
GetCursorPos(&ptCursor);
ScreenToClient(GetConsoleWindow(), &ptCursor);
/** Now ptCursor has the Mouse Position relative to the console client area. **/
COORD dwBufferPosition;
dwBufferPosition.X = ptCursor.x / dwFontWidth;
dwBufferPosition.Y = ptCursor.y / dwFontHeight;
return dwBufferPosition;
}
当字体大约为12x16时,它是准确的。但当字体大小小于10x10时,它就开始出错
我可以让它更准确吗,或者我应该使用其他方法吗?我测试了这个程序,对于小于10x10的字体,它似乎工作得很好,即使没有调用
LPtoDP
,它也工作得很好,但我把它忘在里面了。它调用GetConsoleFontSize
获取字体大小,并将其打印到输出中,以便在缩小字体时检查值。希望能有帮助
#include <Windows.h>
#include <sstream>
#include <iostream>
CONSOLE_FONT_INFO fontInfo;
HANDLE hStdout;
HWND hwnd;
HDC hdc;
COORD CursorToBuffer()
{
POINT ptCursor;
GetCursorPos(&ptCursor);
ScreenToClient(hwnd, &ptCursor);
/** Now ptCursor has the Mouse Position relative to the console client area. **/
COORD dwFontSize = GetConsoleFontSize(hStdout, fontInfo.nFont);
POINT dpFontSize = { dwFontSize.X, dwFontSize.Y };
LPtoDP(hdc, &dpFontSize, 0);
COORD dwBufferPosition;
dwBufferPosition.X = ptCursor.x / dpFontSize.x;
dwBufferPosition.Y = ptCursor.y / dpFontSize.y;
std::string fontSize = "fontSize: " + std::to_string(dpFontSize.x) + ' ' + std::to_string(dpFontSize.y) + "\n";
OutputDebugStringA(fontSize.c_str());
return dwBufferPosition;
}
void writeAt(int x, int y, std::string text)
{
COORD position = { x, y };
SetConsoleCursorPosition(hStdout, position);
std::cout << text;
}
int main()
{
hwnd = GetConsoleWindow();
hdc = GetDC(hwnd);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetCurrentConsoleFont(hStdout, FALSE, &fontInfo);
while (1) {
COORD cursor = CursorToBuffer();
std::string txt = std::to_string(cursor.X) + " " + std::to_string(cursor.Y) + " \n";
writeAt(1, 1, txt);
}
return 0;
}
#包括
#包括
#包括
控制台字体信息字体信息;
处理HST输出;
HWND-HWND;
HDC-HDC;
COORD CursorToBuffer()
{
点光标;
GetCursorPos(&ptCursor);
屏幕到客户端(hwnd和ptCursor);
/**现在,ptCursor具有相对于控制台客户端区域的鼠标位置**/
COORD dwFontSize=GetConsoleFontSize(hStdout,fontinfot.nFont);
点dpFontSize={dwFontSize.X,dwFontSize.Y};
LPtoDP(hdc和dpFontSize,0);
协调位置;
dwBufferPosition.X=ptCursor.X/dpFontSize.X;
dwBufferPosition.Y=ptCursor.Y/dpFontSize.Y;
std::string fontSize=“fontSize:”+std::to_string(dpFontSize.x)+''+std::to_string(dpFontSize.y)+“\n”;
OutputDebugStringA(fontSize.c_str());
返回位置;
}
无效写入(整数x,整数y,标准::字符串文本)
{
坐标位置={x,y};
设置控制台或位置(HST输出,位置);
std::cout比计算鼠标位置更好的是获得其实际值。使用ReadConsoleInput
使用ReadConsoleInput
,您将获得一条带有鼠标事件记录的输入记录
。它还包含鼠标位置
您使用的是GetConsoleFontSize()吗
若要获取dwFontWidth
/dwfontweight`的值,请注意,它返回的大小是以逻辑单位表示的,而不是以像素表示的,因此在计算位置之前,您必须将屏幕坐标从像素转换为逻辑单位。我不知道为什么,但此代码的行为相同。可能是windows版本弄乱了此方法?