Question

I'm trying to figure out how to use the Windows API function PathCompactPath. It needs a handle to a device context (hDC) in addition to a pixel length to which a path string is shortened, where the device context contains information about the font size, font face etc. that is used for the length calculation.

If I have a window handle (hWnd) to a label, how can I properly get a device context which contains the font information with which this label was created? GetDC seems to discard this information for normal window handles.

I'm writing a C++ DLL for use with VB6, so the hWnd would come from a VB6 control. However, I think my question applies to the general case (a label in a C++ form) as well.

Was it helpful?

Solution

I'm assuming your "label" is a static control with text in it. If that's the case, you can simply add the SS_PATHELLIPSIS control style and let the control do the work for you.

But to answer the question as asked:

You can get a DC for the control with GetDC, but, most likely, that DC won't have the right font selected into it. If it does, then you just got lucky, but you don't want the rely on luck. Most controls will let you ask for a handle to the font it would use by sending it a WM_GETFONT message. Using that, you can set up the DC, call PathCompactPath, and then clean up.

auto hdc = ::GetDC(hwnd);
auto hfont = reinterpret_cast<HFONT>(::SendMessage(hwnd, WM_GETFONT, 0, 0));
auto hfontOld = ::SelectObject(hdc, hfont);
blah blah PathCompactPath blah blah
::SelectObject(hdc, hfontOld);
::ReleaseDC(hwnd, hdc);

You'll want to do some error checking, especially to check the return of the WM_GETFONT message--it's possible the control you're querying doesn't support that message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top