0

我想做一个程序,打开一个 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 消息发布到窗口。我从中获得了成功的价值,但窗口保持打开状态。

请帮忙!

4

1 回答 1

0

我找到了这个帖子: 关闭所有浏览器窗口?

它说:

使用 InternetExplorer 对象打开每个窗口并在完成后调用 Quit 方法。这具有仅关闭您打开的窗口的额外好处(这样用户或其他应用程序打开的窗口不受影响)。

https://msdn.microsoft.com/library/aa752127.aspx

我知道这没有多大帮助(缺少片段),但至少有一些帮助。

于 2016-11-08T11:51:48.230 回答