Search code examples
windowswindows-7shellexecute

c++ ShellExecute not working


I am working on a c++ program that is supposed to launch internet explorer and display a local html file on Windows 7. I am trying to use ShellExecute, but it doesn't work. I googled around, but could not find an answer that worked. Here is the code:

ShellExecute(NULL, "open", "start iexplore %userprofile%\\Desktop\\html_files\\file.hml", NULL, NULL, SW_SHOWDEFAULT);

I copied the command into a system() call just to see if it would work, and it did. Here is the system() call I tried:

system("start iexplore %userprofile%\\Desktop\\html_files\\file.html");



Since the system call worked, its clearly a problem with ShellExecute. Basically, Internet Explorer does not come up. Everything compiles correctly, though. Any ideas?


Solution

  • I dont think IE will recognize environment variables in URI's. In fact % have special meaning.

    Something like this should work:

    #include <windows.h>
    
    int main()
    {
         ShellExecute(NULL, "open",
                      "C:\\progra~1\\intern~1\\iexplore.exe",
                      "file:///C:/Users/UserName/Desktop/html_files/file.html",
                      "",
                      SW_MAXIMIZE); 
         return 0;
    }
    

    Another way, obtain the %userprofile% enviroment variable value and concat your URI:

    #if (_MSC_VER >= 1400) 
    #pragma warning(push)
    #pragma warning(disable: 4996)    // Disabling deprecation... bad...
    #endif 
    
    #include <windows.h>
    #include <stdlib.h>
    #include <iostream>
    #include <string>
    
    int main()
    {
         std::string uri = std::string("file:///") + getenv("USERPROFILE") + "/Desktop/html_files/file.txt";
    
         ShellExecute(NULL, "open",
                      "C:\\progra~1\\intern~1\\iexplore.exe",
                      uri.c_str(),
                      "",
                      SW_MAXIMIZE); 
    
         return 0;
    }
    

    Im disabling warnings here, but you should use _dupenv_s instead of getenv.

    Good luck.