我想创建一个打开Windows资源管理器窗口的程序,等待5秒钟,然后关闭窗口。我尝试了以下内容:
#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消息发布到窗口。我从中获得了成功的价值,但窗口保持打开状态。
请帮忙!
答案 0 :(得分:0)
我找到了这个帖子: Close all browser windows?
它说:
使用InternetExplorer对象打开每个窗口并在完成后调用Quit方法。这样做的另一个好处是只关闭您打开的窗口(以便用户或其他应用程序打开的窗口不受影响)。
https://msdn.microsoft.com/library/aa752127.aspx
我知道这没有多大帮助(缺少片段),但至少有些东西。