[C] 关闭指定名称的全部进程

bool KillProcess(DWORD pid)
{
	// When the all operation fail this function terminate the "winlogon" Process for force exit the system.
	HANDLE hYourTargetProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION |   // Required by Alpha
		PROCESS_CREATE_THREAD     |   // For CreateRemoteThread
		PROCESS_VM_OPERATION      |   // For VirtualAllocEx/VirtualFreeEx
		PROCESS_TERMINATE        |
		PROCESS_VM_WRITE,             // For WriteProcessMemory
		FALSE, pid);

	if(hYourTargetProcess == NULL)
	{
		return FALSE;
	}

	if(TerminateProcess(hYourTargetProcess, 0)!=0)
	{
		::Sleep(150);
		return TRUE;
	}
	else
		return FALSE;
}


DWORD CloseProcessIDByName(TCHAR *szProcName)
{

	CString str;
	DWORD dwProcID = 0;
	HANDLE hProcessSnap;
	PROCESSENTRY32 pe32;

	//获取系统中全部进程的快照 Take a snapshot of all processes in the system.
	//TH32CS_SNAPPROCESS:在快照中包含系统中所有的进程。
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (INVALID_HANDLE_VALUE == hProcessSnap) 
		return(FALSE);

	pe32.dwSize = sizeof(PROCESSENTRY32);

	// 获取第一个进程的信息 Retrieve information about the first process,
	// 若获取失败则退出 and exit if unsuccessful
	if (!Process32First(hProcessSnap, &pe32))
	{
		// 清除快照 clean the snapshot object
		CloseHandle(hProcessSnap);
		str.Format( "! Failed to gather information on system processes! \n");
		OutputDebugString(str);
		return(NULL);
	}
	//匹配进程ID Matching Process ID
	do
	{
		if (!strcmp(szProcName,pe32.szExeFile))
		{
			//拷贝进程名 Copy Process Name
			str.Format("%s:%d \n", pe32.szExeFile , pe32.th32ProcessID );

			OutputDebugString(str);
			
			KillProcess(pe32.th32ProcessID);//test

			dwProcID = pe32.th32ProcessID;
		}
		//cout << pe32.szExeFile << endl;
	} while (Process32Next(hProcessSnap, &pe32));

	// 清除快照 clean the snapshot object
	CloseHandle(hProcessSnap);

	return dwProcID;
}

用例:

//采用头文件#include <TlHelp32.h>

//注意某些进程若终结失败,需要你的exe提升到管理员权限来运行才能. 

CloseProcessIDByName("chrome.exe"); //关闭全部谷歌浏览器chorme.exe

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值