程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> Windows編程:開啟/關閉/遍歷程序的類 代碼(C++)

Windows編程:開啟/關閉/遍歷程序的類 代碼(C++)

編輯:關於C++

類包含4個函數, 啟動程序, 遍歷所有進程, 關閉程序, 遍歷進程依賴的動態鏈接庫.

示例: Image.exe是預先生成的可執行程序(exe), 啟動程序, 間隔5秒, 關閉程序.

使用方法參加測試程序.

代碼:

/* 
 * process.h 
 * 
 *  Created on: 2014.06.08 
 *      Author: Spike 
 */
      
/*vs 2012*/
      
#ifndef TRAVERSEPROCESSMODEL_H  
#define TRAVERSEPROCESSMODEL_H  
      
#include <iostream>  
#include <iomanip>  
#include <string>  
#include <map>  
      
#include <windows.h>  
#include <TlHelp32.h>     //snapshot  
      
class Process   
{  
public:  
    bool startProcess (const std::string _name);  
    bool terminateProcess (const std::string _name);  
    bool traverseModels (const std::string _name);  
    bool traverseProcesses (std::map<std::string, int>& _nameID);  
};  
      
#endif //TRAVERSEPROCESSMODEL_H  
      
      
      
      
/* 
 * process.cpp 
 * 
 *  Created on: 2014.06.08 
 *      Author: Spike 
 */
      
/*vs 2012*/
      
#include "process.h"  
      
using namespace std;  
      
bool Process::startProcess (const std::string name)   
{  
    STARTUPINFO si; //參數設置  
    memset(&si, 0, sizeof(STARTUPINFO));  
    si.cb = sizeof(STARTUPINFO);  
    si.dwFlags = STARTF_USESHOWWINDOW;  
    si.wShowWindow = SW_SHOW;  
      
    PROCESS_INFORMATION pi; //參數結束  
      
    /*printf("Please enter the name of process to start:"); 
    std::string name; 
    cin >> name;*/
      
    if (!CreateProcessA(NULL, (LPSTR)name.c_str(), NULL, NULL, FALSE, 0,NULL,NULL,&si,&pi)) {  
        cout<<"Start Process Error!"<<endl;  
        return false;  
    } else {  
        cout<<"Start Process Sucess!"<<endl;  
    }  
    return true;  
}  
      
bool Process::traverseProcesses (std::map<std::string, int>& _nameID)   
{  
    PROCESSENTRY32 pe32;  
    pe32.dwSize = sizeof(pe32);  
      
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);  
    if (hProcessSnap == INVALID_HANDLE_VALUE) {  
        std::cout << "CreateToolhelp32Snapshot Error!" << std::endl;;  
        return false;  
    }  
      
    BOOL bResult =Process32First(hProcessSnap, &pe32);  
      
    while(bResult)   
    {  
        std::string name = pe32.szExeFile;  
        int id = pe32.th32ProcessID;  
      
        //std::cout << "Process Name:" << name << "  " << "ProcessID:" << id<< std::endl;  
    //
		
							
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved