How can I start explorer.exe via C++?

2019-06-21 14:28发布

问题:

I'm trying to programmatically start explorer.exe but I'm not having any luck.

This is my code:

cout << pName << "died, lets restart it." << endl;
STARTUPINFO startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);

PROCESS_INFORMATION processInformation;

if(CreateProcess(pName, NULL, NULL, NULL, false, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation) == 0){
    cout << "Error starting " << pName << ": " << GetLastError() << endl;
}

and pName is explorer.exe

Can someone tell me what I'm doing wrong? I get the error code '2' which is ERROR_FILE_NOT_FOUND

回答1:

The first parameter is the application name; the second is the command line. Try specifying "explorer.exe" as the second parameter.

See this MSDN article:

lpApplicationName [in, optional]

The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer.

The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed.



回答2:

You probably should give "ShellExecuteEx" a try. This function lets you specify a file or folder and a verb that describes what to do with it. If you use "explore" as the verb, it will open Windows Explorer with the given folder.



回答3:

It's surprisingly hard to find relevant information on how to reliably restart windows explorer. On 64-bit Windows 7/8, the ShellExecute method does not work properly and leads to things such as file copying and icon overlays being completely broken.

The most reliable way seems to use stdlib.h system call:

system("start explorer");

If you are trying to shutdown and restart explorer, you might want to programmatically disable AutoRestartShell registry key, which prevents you from controlling when explorer is restarted.