Home > Mobile >  Is typecasting the message when using SendMessageW() always necessary?
Is typecasting the message when using SendMessageW() always necessary?

Time:12-17

Is typecasting the message when using SendMessageW() always necessary, or am I using a "non-ideal" type for my message? If it is not always necessary, what is the type that I would use that would not require it to be cast?

std::wstring LBstring;
...
SendMessageW(hWndList1, LB_ADDSTRING, 0, (LPARAM)LBstring.c_str());

Further, generally, is typecasting never necessary, minimally necessary, or often necessary? When I worked with ANSI C back in the 90s, I was under the impression (maybe falsely) that typecasting was just forcing something to be something it wasn't, and so was undesirable.

CodePudding user response:

When using SendMessage() directly, then yes, the casting is necessary, since it only accepts integer values as parameters, not pointers. But the integers are large enough to hold pointer values, in cases where messages operate on pointers, like LB_ADDSTRING does.

In any case, for this particular situation, you can avoid the casting by using the ListBox_AddString() macro instead:

...
#include <windowsx.h>

std::wstring LBstring;
...
ListBox_AddString(hWndList1, LBstring.c_str());

It handles the casting for you:

#define ListBox_AddString(hwndCtl, lpsz)            ((int)(DWORD)SNDMSG((hwndCtl), LB_ADDSTRING, 0L, (LPARAM)(LPCTSTR)(lpsz)))

Many Win32 UI controls have similar wrapper macros defined for their respective messages.

CodePudding user response:

As Adrian Mole noted in the comments:

The casting of arguments to WinAPI calls is very often necessary, especially for the lParam argument to message functions. This is because those messages often use a pointer for that parameter and the actual LPARAM type is integral.

In C , some form of cast (either 'C-Style' or reinterpret_cast) is absolutely required for those lParam arguments. In C, the implicit conversion rules are a bit less stringent but you still need them in many cases.

  • Related