0

I keep getting this error message:

State Error C2664 -- int MessageBoxW(HWND,LPCWSTR,LPCWSTR,UINT)': cannot convert argument 2 from 'const char *' to 'LPCWSTR' " 31

This is my code below. I understand it has to do with passing a const type through the what() function in the error class. For some reason it's incompatible. Any ideas?

// on startup execute to determine exceptions
try
{
    // instantiate object app of class AppWindow
    AppWindow app;

    // if(initialize function in class app is executed, and while the app is running, broadcast app)
    if (app.init())
    {
        while (app.isRun())
        {
            app.broadcast();
        }
    }
}

// if the following error is found, execute MessageBox function with following parameters
catch (const std::runtime_error& error)
{
    // parameters(has no owner window so displays independently)
    MessageBox(nullptr,  error.what(), L"An error has occured", MB_OK);
}

return 0;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Cody S
  • 3
  • 2
  • An `LPCWSTR` is a pointer to an array of `wchar_t` elements, which are each 16 bits instead of the 8-bit char. – Botje Nov 18 '20 at 16:41
  • 1
    https://stackoverflow.com/questions/17643122/messageboxw-cannot-convert , and https://stackoverflow.com/questions/35726799/visual-studio-2015-winapi-error-on-messagebox , to name but two of the many duplicates, acquired by literally pasting your error message into the search field on this site. When messageboxing narrow character strings, hard-use MessageBoxA. – WhozCraig Nov 18 '20 at 16:45

3 Answers3

2

std::runtime_error::what() returns const char*, so you should use MessageBoxA(), not MessageBox() nor MessageBoxW().

MessageBoxA(nullptr,  error.what(), "An error has occured", MB_OK);

Also don't forget to remove the L prefix from the string literal.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

You can use MessageBoxA() and remove the L prefix from the caption string. Or else convert e.what() to a wchar_t string.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Zeltrax
  • 310
  • 2
  • 10
0
#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK);
    return 0;
}

Using the example from http://www.winprog.org/tutorial/start.html. You will get the C2664 error. To solve it, add an L.

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    MessageBox(NULL, L"Goodbye, cruel world!", L"Note", MB_OK);
    return 0;
}