终止可执行(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:" //更多精彩内容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/ // << 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关闭.
作者:csdn博客 Spike_King
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索c++
, include
, 程序
, 进程
, 代码
32
异常代码 c0000005、贪吃蛇c语言代码、c语言代码、c 代码生成器、c 源代码,以便于您获取更多的相关知识。
时间: 2024-12-31 16:36:04