[C++] GetTextMetrics on global window?

The title says it all, how I can get the text metrics on a global window?

Here's what I'm working with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
case WM_MEASUREITEM: {
  int breaks=1; //Amount of line breaks; there will always be one.
  MEASUREITEMSTRUCT* pmis = (MEASUREITEMSTRUCT*)lParam;
  TEXTMETRIC tm;
  TCHAR text[500];

  //Get Text
  SendMessage(glbWin.mainListbox, LB_GETTEXT, pmis->itemID, (LPARAM)text);
			
  //Calculate height of text
  GetTextMetrics(GetWindowDC(glbWin.mainListbox), &tm);
			
  //Scan for line breaks
  for(int i=0; i<500 && text[i]!='\0'; i++){
    if(text[i]=='\n'){
      breaks++;
    }
  }

  //Set height based on text line-height and number of line breaks
  pmis->itemHeight=(tm.tmHeight*breaks);

  break;


The problem is, GetTextMetrics returns 16, not 18 as it should due to my font declaration

1
2
3
4
HFONT tahoma18=CreateFont(18,0,0,0,400,FALSE,FALSE,FALSE,ANSI_CHARSET,
  OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,FF_DONTCARE,_T("Tahoma"));
/****/
SendMessage(listbox, WM_SETFONT, (WPARAM)tahoma18, true);


The font is properly changed, but I still get 16 when I use GetTextMetrics. Does anybody know what this is happening?

Thanks.
Weird, I''m finding the same thing.
The font size and typeface of the control changes (I used a button for the test) - but
getting the textmetrics of the control always return 16 no matter what font size is actually used.

(when I do the same for the main window, the textmetric returns the expected value)

A way around this problem is as follows:
(For this test I'm using a button - button1 is the window handle.
hdc is the dc of my main window)
1
2
3
4
5
6
    TEXTMETRIC tm;
    HFONT controlFont = (HFONT)SendMessage(button1, WM_GETFONT,0,0); //get font handle from control

    HFONT hOldFont = (HFONT) SelectObject(hdc, controlFont);//select it into main window  HDC
    GetTextMetrics(hdc, &tm); //get textmetrics values
    SelectObject(hdc, hOldFont); //reset main window DC  font 
Last edited on
That's what I found to work after I posted this. I just consolidated it a bit more as I didn't need the backup.

1
2
3
4
TEXTMETRIC tm;
SelectObject(hdc, SendMessage(button1, WM_GETFONT,0,0);
GetTextMetrics(hdc, &tm);
/*...*/
Topic archived. No new replies allowed.