Home > Enterprise >  ShellExecute ends up in error C2065 don't know how to fix
ShellExecute ends up in error C2065 don't know how to fix

Time:12-29

I have a timer, after which a local html file should be executed, but I hit some kind of error:

int delay = 120;
delay *= CLOCKS_PER_SEC;

clock_t now = clock();

while (clock() - now < delay);

string strWebPage = "file:///D:/project/site/scam.html";

strWebPage = "file:///"   strWebPage;
ShellExecute(NULL, NULL, NULL, strWebPage, NULL, SW_SHOWNORMAL);

return 0;

E0413 no suitable conversion function from "std::string" to "LPCWSTR" exists

I'm new to C , so it might be an obvious solution.

Could anyone point me to how I can fix it?

CodePudding user response:

You have two problems.

But first, you should always take the time to read the documentation. For Win32 functions, you can get to a known function by typing something like “msdn ShellExecute” into your favorite search engine and clicking the “Lucky” button.

Problem One

ShellExecute() is a C function. It does not take std::string as argument. It needs a pointer to characters. Hence:

std::string filename = "birds.html";
INT_PTR ok = ShellExecute( 
    NULL,             // no window
    NULL,             // use default operation 
    filename.c_str(), // file to open
    NULL,             // no args to executable files
    NULL,             // no start directory
    SW_SHOWNORMAL );
if (ok <= 32)
  fooey();

Notice that we pass a const char * to the function as the file to <default verb>.

Problem Two

From your image it would appear that you have your application declared as a Unicode application. In other words, somewhere there is a #define UNICODE.

This makes ShellExecute() expect a WIDE character string (const wchar_t *)as argument, not a narrow string (const char *).

You can still use a narrow string by simply specifying that you want the narrow version:

INT_PTR ok = ShellExecuteA(
    ...

I recommend you look at how you set up your project to figure out how you got things to think you were using wide strings instead of narrow strings.

CodePudding user response:

in the winAPI. an LPCWSTR is a Long Pointer to Const Wide String. e.g. a wchar_t (similar to const char*). Your error is complaining that it can't convert between the two types.

To convert an LPCWSTR to a std::string I recommend This answer by Jhonny Mnemonic

just pass the LPCWSTR to the constructor of wstring like this:

LPCWSTR str=L"fun";
string str2(str);

finally you need to convert the std::wstring to a std::string

for this. I recommend This answer by dk123

  •  Tags:  
  • c
  • Related