Search code examples
c++shellexecute

ShellExecute not working or am I doing something wrong?


So, shortly, I need to launch a program with launch options, in my case - Steam. In the beginnings of my little program I've used system() to launch it, now I want to launch it with ShellExecute(), but it does nothing. Any help will be appreciated.

My code:

#include <Windows.h>
#define STEAM_DIRECTORY "D:\\Programs\\Steam\\steam.exe"

int main()
{
    ....
    string arguments = "- login " + login[num - 1] + " " + pass[num - 1];
    ShellExecute(NULL, (LPCWSTR)"open", (LPCWSTR)STEAM_DIRECTORY, (LPCWSTR)arguments.c_str(), NULL, SW_SHOWMINIMIZED);
}

What I've used before:

#define STEAM_DIRECTORY "\"D:\\Programs\\Steam\\steam.exe\""

int main()
{
    ....
    string runsteam_arg = STEAM_DIRECTORY;
    runsteam_arg = runsteam_arg + " -login " + login[num - 1] + " " + pass[num - 1];
    system(runsteam_arg.c_str());
}

Edit: What I need to run in the end:

"D:\Programs\Steam\steam.exe" -login xxxx xxxx     

And one more thing, can somebody explain what CoInitializeEx() does? I'm new to Windows API.


Solution

  • Just type casting the pointers with (LPCWSTR) is not sufficient, you need to convert the string from ANSI to Unicode.

    The simplest (but not the best) solution for you would be to call ShellExecuteA instead.

    #include <Windows.h>
    #define STEAM_DIRECTORY "D:\\Programs\\Steam\\steam.exe"
    
    int main()
    {
        ....
        string arguments = "- login " + login[num - 1] + " " + pass[num - 1];
        ShellExecuteA(NULL, "open", STEAM_DIRECTORY, arguments.c_str(), NULL, SW_SHOWMINIMIZED);
    }
    

    Getting real Unicode strings would require you to write L"str" instead of "str". And you would need to use wstring instead of string.

    #include <Windows.h>
    #define STEAM_DIRECTORY L"D:\\Programs\\Steam\\steam.exe"
    
    int main()
    {
        ....
        wstring arguments = L"- login " + login[num - 1] + L" " + pass[num - 1];
        ShellExecuteW(NULL, L"open", STEAM_DIRECTORY, arguments.c_str(), NULL, SW_SHOWMINIMIZED);
    }
    

    Also: don't forget to CoInitialize() before using ShellExecute(Ex), for example with:

    const HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);