首页 > 代码库 > Windows编程 - 终止可执行(exe)程序 代码(C++)
Windows编程 - 终止可执行(exe)程序 代码(C++)
终止可执行(exe)程序 代码(C++)
本文地址: http://blog.csdn.net/caroline_wendy
终止可执行(exe)程序, 首先遍历进程, 找到进程名称对于的进程ID号, 然后根据进程ID, 终止进程.
示例代码: 包括遍历进程代码, 和关闭代码.
代码:
/* * main.cpp * * Created on: 2014.06.08 * Author: Spike */ /*vs 2012*/ #include <iostream> #include <string> #include <map> #include <windows.h> #include <TlHelp32.h> using namespace std; bool 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); int num(0); while(bResult) { std::string name = pe32.szExeFile; int id = pe32.th32ProcessID; //std::cout << "[" << ++num << "] : " <<"Process Name:" // << name << " " << "ProcessID:" << id<< std::endl; _nameID.insert(std::pair<string, int>(name, id)); //字典存储 bResult = Process32Next(hProcessSnap,&pe32); } CloseHandle(hProcessSnap); return true; } bool terminateProcess (const std::string _name) { DWORD dwId; std::map<std::string, int> nameID; if (!traverseProcesses(nameID)) { //变量进程 cout << "Print Processes Error!" << endl; } /*printf("Please enter the name of process to terminal:"); std::string name; cin >> name;*/ dwId = nameID[_name]; BOOL bRet = FALSE; HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwId); if(hProcess != NULL) bRet = TerminateProcess(hProcess, 0); CloseHandle(hProcess); if(bRet){ std::cout << "Terminate Process Success!" << std::endl; } else { std::cout << "Terminate Process Error!" << std::endl; return false; } return true; } int main() { const std::string program("Image.exe"); if (!terminateProcess(program)) { cout << "Terminate Process Error!" << endl; } return 0; }
注: Image.exe为启动的显示图片的程序, 当执行完成后, Image.exe关闭.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。