user1958850
user1958850

Reputation: 495

WM_GETFONT returns type LRESULT instead of expected HFONT

Doing HFONT childfont = SendMessage (childwin, WM_GETFONT, NULL, NULL); results in the error "invalid conversion from 'LRESULT' to 'HFONT__*'" when MSDN states that the return type is HFONT. What is the proper return type for this function? Should I just use LRESULT or is there something special I have to do because my program will come back and bite me later if I don't do it?

Upvotes: 1

Views: 2521

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400512

SendMessage is a Swiss army knife: it does a lot of different things, all of which return various types of values. Since C does not support overloaded return values (remember that the Win32 API is a C API), it has to return a generic LRESULT type.

So, you need to cast the result to the actual type. The documentation states that it this message returns an HFONT, so you must cast the result to an HFONT:

HFONT childFont = (HFONT)SendMessage(childWin, WM_GETFONT, ...);

Alternatively, you can use the macro GetWindowFont() defined in the header file <WindowsX.h>, which includes a lot of utility macros:

// From WindowsX.h.  SNDMSG is a macro which expands to either SendMessage or
// AfxSendMessage.
#define GetWindowFont(hwnd) FORWARD_WM_GETFONT((hwnd), SNDMSG)
#define FORWARD_WM_GETFONT(hwnd, fn) \
    (HFONT)(UINT_PTR)(fn)((hwnd), WM_GETFONT, 0L, 0L)

// Example usage:
HFONT childFont = GetWindowFont(childWin);

Upvotes: 4

Qaz
Qaz

Reputation: 61970

Since SendMessage is used for many, many purposes, it can't have the perfect return type for everything. In this case, you have to cast it to the type you need:

HFONT childfont = reinterpret_cast<HFONT>(SendMessage(...));

In the handler for WM_GETFONT, you'd expect to see something like the equivalent of this:

HFONT whateverFont;
...
return (LRESULT)whateverFont;

So casting back to the HFONT it was originally is ok.

Upvotes: 4

Related Questions