Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char[] to LPCWSTR

Tags:

visual-c++

Can anyone help me to correct this code:

    char szBuff[64];
    sprintf(szBuff, "%p", m_hWnd);
    MessageBox(NULL, szBuff, L"Test print handler", MB_OK);

The error is, it cant convert the 2nd parameter to LPCWSTR.

like image 498
barlyee Avatar asked Jul 12 '10 03:07

barlyee


2 Answers

For this specific case, the fix is quite simple:

wchar_t szBuff[64];
swprintf(szBuff, L"%p", m_hWnd);
MessageBox(NULL, szBuff, L"Test print handler", MB_OK);

That is, use Unicode strings throughout. In general, when programming on Windows, using wchar_t and UTF-16 is probably the simplest. It depends on how much interaction with other systems you have to do, of course.

For the general case, if you've got an ASCII (or char *) string, use either WideCharToMultiByte for the general case, or mbstowcs as @Matthew points out for simpler cases (mbstowcs works if the string is in the current C locale).

like image 74
Dean Harding Avatar answered Oct 11 '22 18:10

Dean Harding


You might want to look at mbstowcs, which will convert a conventional "one byte per character" string to a "multiple byte per character" string.

Alternatively, change your project settings to use Multibyte Strings - by default they are usually "Unicode" or "Wide Character" strings (I can't remember the exact option name off the top of my head).

like image 33
Matthew Iselin Avatar answered Oct 11 '22 18:10

Matthew Iselin