2012-08-05 312 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

我知道,這沒有太大的幫助(缺少片段),但至少東西。

相關問題