How to get the line width in pixels (/ logical units)?

I am following a tutorial here to add a horizontal scrollbar to a list control. Everything works there, except for the TextWidth () function (VC ++ 2012 says that it is undefined), so I found this question. But I do not know how to initialize hdc, so I tried this . But GetTextExtentPoint32 continues to return zero.

Any idea how I can solve this?

My code looks like this (after editing):

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

(szMessage contains user input)

+8
c ++ c string windows winapi
source share
2 answers

Good to answer my question: The code above (see Question) gives too high a value for Size.cx, because MESSAGE_SIZE is 1000, not the size of the actual row, so instead I used strMessage.c_str and strMessage.size () . This still gave some slight inaccuracies with the output, I assumed that it was due to the wrong font, so I manually made the font. Now it gives the correct value for Size.cx. Now the code is as follows:

 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; } } 

further in the code:

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

Edit:

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

It works too and does not require you to make a font or edit the font of the control

+3
source share

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); 
+4
source share

All Articles