c++ - 在 shellexecute 中传递文件路径作为参数

标签 c++ shellexecute createprocess

我希望我的其他 C++ 程序从另一个文件运行,所以我使用 shell 执行。 Mu代码是:

#pragma comment(lib,"shell32.lib")  
#include "windows.h"
#include<Shellapi.h>

#include<stdio.h>
#include<iostream>
using namespace std;

class spwan{
public:
    //char szPath[] = "";
    void run(char path[]);
};

void spwan::run(char szPath[]){
HINSTANCE ShellExecute(HWND,  "open", szPath,"","",SW_SHOW);    
    cout<<"program executed";
}

int main ()
{
 spwan s;
 s.run("path to the file");
}

但是我遇到了类似于预期的带有“open”的类型说明符的问题,并且我无法使用 szPath 定义路径。任何帮助。

错误更具体地说是: 它给我行错误: HINSTANCE ShellExecute(HWND, "open", szPath,"","",SW_SHOW);作为语法错误:'字符串'

当我给出这样的路径时:- C:\Users\saira\Documents\Visual Studio 2010\Projects\phase_1_solver\Debug\phase_1_solver.exe 它给出的错误如下:警告 C4129: 's' : 无法识别的字符转义序列警告 C4129:“D”:无法识别的字符转义序列

最佳答案

在您的代码中:

HINSTANCE ShellExecute(HWND,  "open", szPath,"","",SW_SHOW);

这是一个函数的声明。我认为您实际上是想调用该函数:

HINSTANCE retval = ShellExecute(HWND,  "open", szPath,"","",SW_SHOW);

现在,这也无法编译。由于 HWND 是一种类型。我认为你需要:

HINSTANCE retval = ShellExecute(0, "open", szPath, NULL, NULL, SW_SHOW);

此外,无需实际指定动词。路径的默认动词就足够了。

HINSTANCE retval = ShellExecute(0, NULL, szPath, NULL, NULL, SW_SHOW);

听起来好像您正在传递这样的字符串:

s.run("C:\Users\saira\...\phase_1_solver.exe");

这不好,因为反斜杠在 C++ 中用作转义字符。所以你需要转义它:

s.run("C:\\Users\\saira\\...\\phase_1_solver.exe");

如果您不打算测试返回值,那么您可以简单地编写:

ShellExecute(0, NULL, szPath, NULL, NULL, SW_SHOW);

如果您确实想检查从 ShellExecute 返回时是否有错误,那么 ShellExecute 是一个不好调用的函数。它的错误处理能力特别弱。请改用 ShellExecuteEx。 Raymond Chen 在 Why does ShellExecute return SE_ERR_ACCESSDENIED for nearly everything? 中讨论了 ShellExecute 的错误处理

关于c++ - 在 shellexecute 中传递文件路径作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342605/

相关文章:

C++ 从 CreateProcess() 获取 UTF-8 输出

c++ - 接收 “Undefined symbols for architecture x86_64”

c++ - 在 C++ 实例中,字段未初始化为其默认值。静态字段怎么样?

c++ 没有将值插入注册表

shellexecute - shell脚本符号 ": >"

c++ - 从服务启动进程

winapi - 如何在 XP 兼容模式下启动另一个进程?

c++ - 远程桌面库

c++ - 使用 ShellExecute Properties Verb 的特定属性选项卡

c# - 无论如何在生成进程时指定 PrintTo 打印机?