c++ - DrawTextA() 的结果不理想

标签 c++ mfc

调用 DrawText() 时,我没有得到想要的结果。我想要 Checkbox 控件的文本宽度。但它比它应该的更宽。 我不想要标有红色的部分。

enter image description here

DrawTextA(strText, strlen(strText), *pclRect, DT_CALCRECT | DT_NOPREFIX | DT_SINGLELINE);
int iLength = pclRect->right - pclRect->left;

知道如何获得绝对值吗? 我可以使用不同的标志来获得我想要的结果吗?

编辑:

    SIZE sz;
    HFONT font = (HFONT)pCWnd->GetFont(); //(pCWnd is my CButton)
    HDC hdc = GetDC(NULL);
    SelectObject(hdc, font);

    GetTextExtentPoint32(hdc, strText, strText.GetLength(), &sz);
    ReleaseDC(NULL, hdc);

最佳答案

这是获取文本长度的简单代码。要做任何有用的事情,您需要复选框、主题数据等的尺寸。

void CMyWnd::foo()
{
    CWnd *check = GetDlgItem(IDC_CHECK1);
    if (check)
    {
        CString str;
        check->GetWindowText(str);

        CClientDC dc(this);
        dc.SelectObject(GetFont());
        int width = dc.GetTextExtent(str).cx; //get width

        //test to see where the lines are
        CRect rcheck;
        check->GetWindowRect(&rcheck); //rect in screen coordinates

        POINT pt = { 0 };
        ScreenToClient(&pt);
        rcheck.OffsetRect(pt);  //rect is relative to top-left of parent

        dc.SelectObject(GetStockObject(NULL_BRUSH));
        dc.SelectObject(GetStockObject(BLACK_PEN));

        dc.MoveTo(rcheck.right, rcheck.bottom + 1);
        dc.LineTo(rcheck.right - w, rcheck.bottom + 1);
    }
}

关于c++ - DrawTextA() 的结果不理想,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34421452/

相关文章:

java - {c++} Vertex* myList 和 {java} List myList 有何相似之处?

c++ - 字符串作为文件名

c++ - 奇怪的重复模式和 Sfinae

c++ - Qt 中是否有与 MFCs OnUpdate 等效的功能?

c++ - 有没有比 SHGetPathFromIDList() 更好的方法将 itemidlist 转换为路径字符串?

c++ - 如何解决MFC uArt中未定义的智能感知标识符?

c++ - 为 QWidget 添加约束到 css 文件

c++ - 在 C++20 中将多个范围适配器连接成一个范围

c++ - 如何迭代 CString 并将其字符与 int 进行比较?

python - 一个简单的 python 程序无法访问我的 dll