简体   繁体   English

如何获取字符串的宽度(以像素为单位)(/逻辑单位)?

[英]How to get the width of a string in pixels(/logical units)?

I am following a tutorial here , to add a horizontal scrollbar to a list control. 我在这里按照教程,将一个水平滚动条添加到列表控件。 Everything there works except the TextWidth() function (VC++ 2012 says it's undefined) so I found this question. 除了TextWidth()函数之外的所有东西都有用(VC ++ 2012说它未定义)所以我发现了这个问题。 But I have no idea how to initialize a hdc, so I tried this . 但我不知道如何初始化hdc,所以我尝试了这个 But GetTextExtentPoint32 keeps returning zero. 但GetTextExtentPoint32保持返回零。

Any idea how I can solve this? 知道如何解决这个问题吗?

My code looks like this (after edit): 我的代码看起来像这样(编辑后):

SIZE Size;
HDC hdc=GetDC(hWnd);
iResult=GetTextExtentPoint32(hdc, szMessage, MESSAGE_SIZE, &Size);

(szMessage contains user input) (szMessage包含用户输入)

My way: 我的方式:

SIZE sz;
HFONT font = GetFont();     //GetFont() is part of WTL. If using raw WinAPI it needs to get font in other means.
HDC hdc = GetDC(NULL);
SelectObject(hdc, font);    //attach font to hdc

GetTextExtentPoint32(hdc, text, lstrlenW(text), &sz);
ReleaseDC(NULL, hdc);

Ok so to answer my question: The code above (see question) gives a way too high value for Size.cx because MESSAGE_SIZE is 1000 and not the size of the actual string so I used strMessage.c_str and strMessage.size() instead. 好的回答我的问题:上面的代码(请参阅问题)为Size.cx提供了一个太高的值,因为MESSAGE_SIZE是1000而不是实际字符串的大小所以我使用strMessage.c_str和strMessage.size()代替。 This still gave some small inaccuracies with the output, I assumed this was because the wrong font was used, so I manually made a font. 这仍然给输出一些小的不准确,我认为这是因为使用了错误的字体,所以我手动制作了一个字体。 Now it gives a correct value for Size.cx. 现在它为Size.cx提供了正确的值。 The code now looks like this: 代码现在看起来像这样:

int iHorExt=0;
SIZE Size;
int iCurHorExt=0 // iCurHorExt is actually a global var to prevent it from being reset to 0 evertime the code executes
string strMessage="Random user input here!"

HDC hdc=GetDC(hDlg);

//Random font
HFONT hFont=CreateFont(15, 5, NULL, NULL, FW_MEDIUM, false, false, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_ROMAN, "Times New Roman");

//change font of the control
SendDlgItemMessage(hDlg, IDC_LIST1, WM_SETFONT, (WPARAM)hFont, true);


SelectObject(hdc, hFont);

int iResult=GetTextExtentPoint32(hdc, strMessage.c_str(), strMessage.size(), &Size);
if(iResult!=0)
{
    iHorExt=Size.cx;
    if(iHorExt>iCurHorExt)
    {
        iCurHorExt=iHorExt;
    }
}

later in the code: 稍后在代码中:

SendDlgItemMessage(hDlg, IDC_LIST1, LB_SETHORIZONTALEXTENT, iCurHorExt, NULL);

Edit: 编辑:

SelectObject(hdc, (HFONT)SendDlgItemMessage(hDlg, IDC_LIST1, WM_GETFONT, NULL, NULL));

Works too and doesn't require you to make a font or edit the font of the control 也适用,不需要您制作字体或编辑控件的字体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM