windows 根据HWND获取进程名字 和结束进程源码

来源:互联网 发布:蝴蝶折刀淘宝哪里买 编辑:程序博客网 时间:2024/05/18 16:55

根据HWND获取进程名字

#include <string>#include <windows.h>#pragma comment(lib, "user32.lib")#include <Tlhelp32.h>#pragma comment(lib, "Kernel32.lib")using namespace std;wstring GetProcessNameByHandle(HWND nlHandle){    wstring loStrRet=L"";    //得到该进程的进程id    DWORD ldwProID;    GetWindowThreadProcessId(nlHandle,&ldwProID);    if(0==ldwProID)        return L"";    HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    if(handle==(HANDLE)-1)     {        //AfxMessageBox(L"CreateToolhelp32Snapshot error");        return false;    }    PROCESSENTRY32 procinfo;    procinfo.dwSize = sizeof(PROCESSENTRY32);    BOOL more=::Process32First(handle,&procinfo);    while(more)    {        if(procinfo.th32ProcessID==ldwProID)        {            loStrRet=procinfo.szExeFile;            CloseHandle(handle);            return loStrRet;        }        more=Process32Next(handle,&procinfo);     }    CloseHandle(handle);    return loStrRet;}

结束进程

///停止服务进程//0是失败,1是成功,-1没有发现int StopProcess(LPCSTR ProcessName){HANDLE hSnaphot = NULL;BOOL bMore = FALSE;int nSucess = -1;char Service_EXE[64]= {0};USES_CONVERSION;memset(Service_EXE,0,64);strncpy(Service_EXE,ProcessName,strlen(ProcessName));hSnaphot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);if(hSnaphot == (HANDLE)-1){return 0;}PROCESSENTRY32 pe32;pe32.dwSize = sizeof(pe32);    bMore = Process32First(hSnaphot,&pe32);while(bMore){if(strcmp(Service_EXE,T2A(pe32.szExeFile))==0){// 是我们要结束的进程// #提升进程权限(根据需要没准会被报毒)HANDLE hProcess =  OpenProcess(PROCESS_TERMINATE, FALSE,pe32.th32ProcessID);if(hProcess != NULL){// 结束掉进程if(TerminateProcess(hProcess,0)==0){nSucess = 0;}else{nSucess = 1;}// 根据需要一下子结束掉所有的同名字的进程CloseHandle(hProcess);}else{nSucess = 0;}}bMore = Process32Next(hSnaphot,&pe32);}CloseHandle(hSnaphot);return nSucess;}


原创粉丝点击