【问题标题】:c++ ShellExecute not workingc ++ ShellExecute不起作用
【发布时间】:2015-05-09 00:36:48
【问题描述】:

我正在开发一个应该启动 Internet Explorer 并在 Windows 7 上显示本地 html 文件的 c++ 程序。我正在尝试使用 ShellExecute,但它不起作用。我四处搜索,但找不到有效的答案。这是代码:

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

我将命令复制到 system() 调用中只是为了查看它是否可以工作,并且确实可以。这是我尝试的 system() 调用:

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



由于系统调用有效,它显然是 ShellExecute 的问题。基本上,Internet Explorer 不会出现。不过,一切都正确编译。有什么想法吗?

【问题讨论】:

    标签: windows windows-7 shellexecute


    【解决方案1】:

    用户的shell文件夹的路径,包括桌面,可以由用户自定义,所以%userprofile\desktop不能保证在所有系统上都是正确的路径。获取用户实际桌面路径的正确方法是使用SHGetFolderPath(CSIDL_DESKTOPDIRECTORY)SHGetKnownFolderPath(FOLDERID_Desktop)

    您不需要知道 iexplorer.exe 的路径,Windows 知道如何找到它。因此,只需将“iexplorer.exe”本身指定为lpFile 参数,并将HTML 文件名指定为lpParameter 参数:

    ShellExecute(NULL, "open", "iexplore.exe", "full path to\\file.hml", NULL, SW_SHOWDEFAULT);
    

    话虽如此,这是非常特定于 IE 的。如果要在用户的默认 HTML 浏览器/查看器中加载文件,请将 lpVerb 参数设置为 NULL,并将 HTML 文件设置为 lpFile 参数:

    ShellExecute(NULL, NULL, "full path to\\file.hml", NULL, NULL, SW_SHOWDEFAULT);
    

    这就像用户在 Windows 资源管理器中双击文件一样。

    【讨论】:

    • 是的,这样好多了。
    【解决方案2】:

    我认为 IE 不会识别 URI 中的环境变量。其实%有特殊含义。

    这样的事情应该可以工作:

    #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;
    }
    

    另一种方式,获取 %userprofile% 环境变量值并连接您的 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;
    }
    

    我在这里禁用警告,但您应该使用_dupenv_s 而不是getenv

    祝你好运。

    【讨论】:

    • 你是对的; ie 不适用于 %- 我只是测试了它。你知道 %userprofile% 的替代品吗?
    • 好吧,您可以使用:getenv ("USERPROFILE"); 获取环境变量的值并将其保存到字符串中。然后拨打ShellExecute
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2021-12-14
    相关资源
    最近更新 更多