ShellExecuteEx function always returning error code 5 (C++)

假如想象 提交于 2019-12-25 04:19:18

问题


I need to start a process and have access to the PID, so I am trying to use ShellExecuteEx. I am attempting to open a batch file. However, no matter how I pass the parameters and no matter where the file is located and what permission's I have on the file, the function is returning with Error Code 5: Access is denied.

  • The File is located in the same location as the config files that have already been read successfully.
  • The File is set for full access permissions with any user.
  • It does this with any file type. I've tried just opening text files with the same outcome (Error 5)
  • If I use ShellExecute() instead, the batch file is run successfully.

Here is some of the code I've tried:

SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
exInfo.lpVerb = "open";
exInfo.lpFile = "C:\\batchtest.bat";
exInfo.nShow = SW_NORMAL;
BOOL hReturnCode = ShellExecute(&exInfo);
DWORD LastError = GetLastError();

I've also tried:

SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
exInfo.lpVerb = "open";
exInfo.lpFile = "C:\\Windows\\system32\\cmd.exe";
exInfo.lpParameters = "batchtest.bat";

And many variations of the above.

Also, I've tried something really simple like from here: Get PID from ShellExecute

to no avail.

However this:

ShellExecute(NULL, "open", "C:\\testbat.bat", NULL, NULL, SW_SHOWNORMAL);

works without an error. Unfortunately, I need the PID, so I can't use ShellExecute.

Any suggestions would be greatly appreciated. I feel like I've exhausted all of my options.

Environment: VS 2008 Windows 7

EDIT: fixed the code to "C:\batchtest.bat"; as suggested. (Still same result)


回答1:


Figured it out.
In order to run batch file and I guess some other types of exe's on Windows 7, you have to elevate the call using the lpVerb = _TEXT("runas") -- even if you have UAC turned off. This isn't documented in the SHELLEXECUTEINFO structure documentation on MDSN (it isn't even given as an option), since it says: "The following verbs are commonly used" The final code was as follows:

SHELLEXECUTEINFO exInfo;
exInfo.cbSize = sizeof(SHELLEXECUTEINFO);
exInfo.fMask = SEE_MASK_NOCLOSEPROCESS; //allows the PID to be returned
exInfo.hwnd = NULL;
exInfo.lpVerb =  _TEXT("runas"); //elevates for Windows 7
exInfo.lpFile = "C:\\BatchTest.bat";
exInfo.lpParameters = NULL;
exInfo.nShow = SW_MAXIMIZE;
exInfo.hInstApp = NULL;
exInfo.lpDirectory = NULL;
BOOL hReturnCode = ShellExecuteEx(&exInfo);

I hope that helps others out.




回答2:


Shouldn't the line

exInfo.lpFile = "C:\\batchtest.exe";

be

exInfo.lpFile = "C:\\batchtest.bat";


来源:https://stackoverflow.com/questions/24761582/shellexecuteex-function-always-returning-error-code-5-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!