Search code examples
c++visual-c++visual-studio-2012lpcwstr

LPCWSTR error; is there a better solution?


I have the following c++ code, and it seems like everywhere I attempt to put a string, I have to convert it in order to avoid a `Cannot conver parameter 2 from 'const char[x] to LPCWSTR. I know I can fix this issue by doing a simple conversion, but is there any way around having to convert practically every string I provide? I am a c# developer learning c++ so I'm guessing I'm missing some fundamental concept of the language, if someone could shed some light on this, I'd be grateful!

#include <Windows.h>
#include <string>
using namespace std;

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   PSTR cmdLine,
                   int showCmd)
{
    MessageBox(0, "First Win32 Program.", "My App", MB_OK);
}

Is there a better solution than just this:

{
    MessageBox(0, (LPCWSTR)"First Win32 Program.", (LPCWSTR)"My App", MB_OK);
}

And for some odd reason my application is coming up in Japanese or Chinese. So lost on this one.

enter image description here


Solution

  • Use L"text" to create your strings. This way you're creating a wide string which most-likely are expected from the WinAPI.

    #include <Windows.h>
    #include <string>
    using namespace std;
    
    int WINAPI WinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       PSTR cmdLine,
                       int showCmd)
    {
        MessageBox(0, L"First Win32 Program.", L"My App", MB_OK);
    }
    

    The problem is you're injecting a narrow string by using a C-style cast to LPCWSTR. So two of your narrow chars (8 bit each) will end mixed-up in one UNICODE char (16 bit each).