我确信有某种方法可以使 CreateProcess 和 ShellExecute 与此一起使用,但我怀疑最简单的方法将是旧的 system,例如system("explorer /n, /select,c:\\123.doc").
只是因为它困扰着我,我继续编写了一个简单的程序,用 CreateProcess 来完成这个:
#define UNICODE
#include <windows.h>
#include <string>
void SimpleWriteConsole(std::wstring msg) {
DWORD written = 0;
WriteConsole( GetStdHandle(STD_OUTPUT_HANDLE),
msg.c_str(), msg.length(), &written, NULL);
}
int wmain(int argc, wchar_t **argv, wchar_t **envp) {
SimpleWriteConsole(L"Opening explorer...\n");
std::wstring commandLine = L"explorer /n, /select,";
if( argc < 2 ) {
SimpleWriteConsole(L"Please include a file to select.\n");
return EXIT_FAILURE;
}
commandLine += argv[1];
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION procInfo;
if( ! CreateProcess(NULL, const_cast<wchar_t*>(commandLine.c_str()),
NULL, NULL, 0, 0, NULL, NULL, &startupInfo, &procInfo) ) {
SimpleWriteConsole(L"Couldn't create process :(\n");
return EXIT_FAILURE;
}
CloseHandle( procInfo.hThread );
CloseHandle( procInfo.hProcess );
SimpleWriteConsole(L"Hooray launched explorer.\n");
return EXIT_SUCCESS;
}
它将 C:\abc.txt 部分作为命令行上的参数。没有额外的 dos 框,不会占用您现有的进程(exec 应该这样做,顺便说一句),并且它不使用已弃用的 API。