VanPers
VanPers

Reputation: 339

convert from char to LPCWSTR

I learn Win API with C++ (I'm newbie). I have problem with character/ string data type.

I also read others docs in google but still don't understand.

Today I meet this problem :

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    RECT rect;
    char MyChar = 0;

    switch (message)
    {
    case WM_CHAR:
        MyChar = LOWORD(wParam);
        MessageBox(hWnd, (LPCWSTR)MyChar, (LPCWSTR)MyChar, MB_OK);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

Purpose: Type 1 character and messageBox display it.

My problem is MyChar is a char (8 bits), i want to convert to LPCWSTR. But,... not success.

Anyone can help me. Thanks in advance!

Upvotes: 3

Views: 2363

Answers (4)

Derzu
Derzu

Reputation: 7156

You can do a simple casting operation, casting the (char*) to (wchar_t*).

Example:

char text1[] = "My text vector char";
std::string text2 = "My text std::string";

wchar_t * lpcText1 = (wchar_t *) text1;
wchar_t * lpcText2 = (wchar_t *) text2.c_str();

Upvotes: 0

Luis
Luis

Reputation: 1235

LPCWSTR is expected to be the address of an array of wide chars (wchar_t), and MessageBox() expects that array to end in a null character.

You can then use an array with two elements, use the null character in the second one, and modify the first one like this

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    RECT rect;
    wchar_t myString[2];
    myString[1] = '\0'; // Ensure the second element is the null char

    switch (message)
    {
    case WM_CHAR:
        myString[0] = LOWORD(wParam); // Modify the first element only
        MessageBox(hWnd, myString, myString, MB_OK);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

Upvotes: 2

wshcdr
wshcdr

Reputation: 967

char a[] = "hello";

WCHAR wsz[64];
swprintf(wsz, L"%S", a);

LPCWSTR p = wsz;

Upvotes: 1

Cory Nelson
Cory Nelson

Reputation: 30031

With WM_CHAR, wParam is a UTF-16 code unit -- so, already a value you can store in wchar_t:

wchar_t mystr[2];
mystr[0] = (wchar_t)wParam;
mystr[1] = 0;

MessageBox(hWnd, mystr, mystr, MB_OK);

You may want to use WM_UNICHAR instead, where wParam is a UTF-32 code point.

Upvotes: 0

Related Questions