首页 > 解决方案 > 确定鼠标光标所在的控制台上的角色

问题描述

众所周知,控制台缓冲区大小是由一个二维数组组成的。我正在尝试实现on click buttons(绘制的按钮不是子窗口),但我遇到了准确性问题。

因为Console Window是可移动和可调整大小的,所以我必须采用Mouse Cursor相对于Console Window左上角的位置(我找到了一种以像素为单位准确执行此操作的方法)。但是现在问题来了。当我试图找出哪个character squareMouse Cursoron 时,它变得不准确(大约 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))
                 );

标签: c++winapiconsolemouse

解决方案


您可以更改GetCursPosRelWin为:

POINT GetCursPosRelWin(HWND hWindow)
{
    POINT ptCursor;
    GetCursorPos(&ptCursor);

    ScreenToClient(hWindow, &ptCursor);

    return ptCursor;
}

MoveConsoleCursor致电:

MoveConsoleCursor(ptCursor.x / GetCurrentFontWidth(), ptCursor.y / GetCurrentFontHeight());

如果滚动条没有移动,这会将光标放在正方形的中心。否则,您必须考虑滚动条偏移量。


推荐阅读