0
我想打开一个程序,打开一个Windows资源管理器窗口,等待5秒钟,然后关闭窗口。我试过以下内容:在windows上使用C++打开和关闭应用程序
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
void _tmain(int argc, TCHAR *argv[]) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if(argc != 2) {
cout << "Usage: " << argv[0] << "<path>";
return;
}
// Build the command string.
wstring app = L"explorer.exe ";
wstring str_command = app + argv[1];
wchar_t* command = const_cast<wchar_t*>(str_command.c_str());
// Open the window.
if(!CreateProcess(NULL, // No module name (use command line)
command, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
) {
cout << "CreateProcess failed: " << GetLastError();
return;
}
cout << "Opened window!" << endl;
// Wait for it.
Sleep(5000);
cout << "Done waiting. Closing... ";
// Close explorer.
HANDLE explorer = OpenProcess(PROCESS_TERMINATE, false, pi.dwProcessId);
if(!explorer) {
cout << "OpenProcess failed: " << GetLastError();
return;
}
if(!TerminateProcess(explorer, 0)) {
cout << "TerminateProcess failed: " << GetLastError();
return;
}
// Close process and thread handles.
CloseHandle(explorer);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
cout << "Done.";
}
我把它打开得不错,但我无法把它关闭。 TerminateProcess失败,错误代码为5.我也尝试将WM_CLOSE消息发布到窗口。我从中获得了成功价值,但窗口保持打开状态。
请帮忙!
打开窗户仅需5秒钟的目的是什么? – 2012-08-05 22:57:03
错误代码是:权限被拒绝 – sehe 2012-08-05 22:58:53
您是否尝试了更普通的应用程序,而不是explorer.exe?我担心一个资源管理器进程可能只是指示现有的窗口管理器进程来创建一个新窗口或类似的东西。 – aschepler 2012-08-05 23:14:53