Bio*_*cle 8 c c++ windows string winapi
我在这里按照教程,将一个水平滚动条添加到列表控件.除了TextWidth()函数之外的所有东西都有用(VC++ 2012说它未定义)所以我发现了这个问题.但我不知道如何初始化hdc,所以我尝试了这个.但GetTextExtentPoint32保持返回零.
知道如何解决这个问题吗?
我的代码看起来像这样(编辑后):
SIZE Size;
HDC hdc=GetDC(hWnd);
iResult=GetTextExtentPoint32(hdc, szMessage, MESSAGE_SIZE, &Size);
Run Code Online (Sandbox Code Playgroud)
(szMessage包含用户输入)
我的方式:
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);
Run Code Online (Sandbox Code Playgroud)
好吧,回答我的问题:上面的代码(参见问题)为 Size.cx 提供了太高的值,因为 MESSAGE_SIZE 是 1000 而不是实际字符串的大小,所以我使用 strMessage.c_str 和 strMessage.size() 代替。这仍然会给输出带来一些小误差,我认为这是因为使用了错误的字体,所以我手动制作了一种字体。现在它给出了 Size.cx 的正确值。代码现在看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
稍后在代码中:
SendDlgItemMessage(hDlg, IDC_LIST1, LB_SETHORIZONTALEXTENT, iCurHorExt, NULL);
Run Code Online (Sandbox Code Playgroud)
编辑:
SelectObject(hdc, (HFONT)SendDlgItemMessage(hDlg, IDC_LIST1, WM_GETFONT, NULL, NULL));
Run Code Online (Sandbox Code Playgroud)
也可以工作,不需要您制作字体或编辑控件的字体
归档时间: |
|
查看次数: |
4835 次 |
最近记录: |