代码步骤
获取静态控件的窗口句柄。
获取静态控件的窗口矩形。
获取控件文本内容。
计算字母在控件中的相对位置。
将相对位置转换为屏幕坐标。
void GetCharScreenPosition(int controlID, int charIndex, POINT& charPos)
{
// 获取控件指针
CWnd* pWnd = GetDlgItem(controlID);
if (!pWnd)
return;
// 获取控件句柄
HWND hStatic = pWnd->GetSafeHwnd();
if (!hStatic)
return;
// 获取控件文本
CString text;
GetDlgItemText(controlID, text);
if (text.IsEmpty() || charIndex >= text.GetLength())
return;
// 获取控件窗口矩形
RECT rect;
::GetWindowRect(hStatic, &rect);
// 获取设备上下文
HDC hdc = ::GetDC(hStatic);
// 计算要获取的字母前面的文本宽度
CString subText = text.Left(charIndex);
SIZE subTextSize;
::GetTextExtentPoint32(hdc, subText, subText.GetLength(), &subTextSize);
// 计算字母的宽度
CString charText = text.Mid(charIndex, 1);
SIZE charTextSize;
::GetTextExtentPoint32(hdc, charText, charText.GetLength(), &charTextSize);
// 释放设备上下文
::ReleaseDC(hStatic, hdc);
// 计算字母在屏幕上的位置
charPos.x = rect.left + subTextSize.cx + charTextSize.cx / 2;
charPos.y = rect.top + (rect.bottom - rect.top) / 2;
}
调用示例
假设控件ID是 IDC_STATIC_CONTROL_ID,要获取第一个字母的位置,可以这样调用:
POINT charPos;
GetCharScreenPosition(IDC_STATIC_CONTROL_ID, 0, charPos);
注意事项
确保 GetDlgItem 返回的指针不为空。
在调用 GetTextExtentPoint32 时,要确保设备上下文(HDC)有效。
释放设备上下文时使用 ::ReleaseDC,而不是成员函数 ReleaseDC,因为我们使用了 ::GetDC。