在shellexecute中将文件路径作为参数传递

时间:2013-03-11 15:36:29

标签: 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定义路径。 Anyhelp。

更具体的错误是: 它给我行错误:HINSTANCE ShellExecute(HWND,“open”,szPath,“”,“”,SW_SHOW);作为语法错误:'string'

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

1 个答案:

答案 0 :(得分:2)

在您的代码中,您有:

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的错误处理
相关问题