I have moved my strings to resources and luckily I have LPCTSTR
operator to instantiate strings conveniently like:
CString str( (LPCTSTR) IDS_MY_STRING);
Now I want to do similar type casting with MessageBox()
so it loads the strings from resources as well so I go about like this:
MessageBox( hWnd, (LPCTSTR) IDS_MY_STRING , _T("Error"), MB_RETRYCANCEL);
But this doesn't work, it compiles but crashes at run time. Now the following does work:
MessageBox( hWnd, (CString) (LPCTSTR) IDS_MY_STRING , _T("Error"), MB_RETRYCANCEL);
My question is that MessageBox()
takes LPCTSTR
as 2nd parameter anyways so why do we have to typecast additionally from LPCTSTR
to CString
to make this work?
Others have explained the details of type casts, etc.
Moreover, to simplify your code, you may want to #define
a convenient macro like this:
#define _S(id) (CString(LPCTSTR(id)))
and then use it with MessageBox
(or for other LPCTSTR
parameters as well):
MessageBox( hWnd, _S(IDS_MY_STRING), _S(IDS_TITLE), MB_RETRYCANCEL );