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关闭.


Windows编程 - 终止可执行(exe)程序 代码(C++)




Windows编程 - 终止可执行(exe)程序 代码(C++),布布扣,bubuko.com

Windows编程 - 终止可执行(exe)程序 代码(C++)

上一篇:VC++环境下多文档模板应用程序开发(带源码)


下一篇:Android中的ContentValues用法