2012-08-05 311 views
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消息发布到窗口。我从中获得了成功价值,但窗口保持打开状态。

请帮忙!

+0

打开窗户仅需5秒钟的目的是什么? – 2012-08-05 22:57:03

+0

错误代码是:权限被拒绝 – sehe 2012-08-05 22:58:53

+2

您是否尝试了更普通的应用程序,而不是explorer.exe?我担心一个资源管理器进程可能只是指示现有的窗口管理器进程来创建一个新窗口或类似的东西。 – aschepler 2012-08-05 23:14:53

回答

0

我发现这个线程: Close all browser windows?

它说:

使用InternetExplorer对象打开每个窗口,并在完成后调用退出方法。这有附加好处,只关闭你打开的窗口(这样用户或其他应用程序打开的窗口不受影响)。

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

我知道,这没有太大的帮助(缺少片段),但至少东西。

相关问题