获取进程pid、根据进程pid获取线程pid、获取线程进程句柄

=======================================

获取进程pid

=======================================

#include "tlhelp32.h"

//获取PID
UINT GetProPid(LPCTSTR pszExeFile)
{
 //查找当前的进程的pid
 UINT nProcessID = 0;
 PROCESSENTRY32 pe = {sizeof(PROCESSENTRY32)};
 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
 if (hSnapshot != INVALID_HANDLE_VALUE)
 {
  if (Process32First(hSnapshot, &pe))
  {
   while (Process32Next(hSnapshot, &pe))
   {
    if (lstrcmpi(pszExeFile, pe.szExeFile) == 0)
    {
     nProcessID = pe.th32ProcessID;
     break;
    }
   }
  }
  CloseHandle(hSnapshot);
 }
 return nProcessID;
}

 

//调用

UINT dwProcessID=GetProPid(_T("explorer.exe"));

=======================================

根据进程pid获取线程pid

=======================================

DWORD dwThreadID;

THREADENTRY32 te32 = {sizeof(te32)};
  HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0);
  if( Thread32First( hThreadSnap, &te32) )
  {
   do{
    if( dwProcessID == te32.th32OwnerProcessID )
    {
     dwThreadID = te32.th32ThreadID;
     break;
    }
   }while( Thread32Next( hThreadSnap, &te32) );
  }

=======================================

根据进程id获取进程名

=======================================

BOOL   GetProcess(int   nID)

{

CString strName;  
  HANDLE hProcessSnap=NULL;  
  PROCESSENTRY32 pe32={0};  
  hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);  
  if(hProcessSnap==(HANDLE)-1)  
  {  
   ::MessageBox(NULL,L"查询进程失败!:(",L"错误提示",MB_OK);  

   return   FALSE;
  }  
  pe32.dwSize=sizeof(PROCESSENTRY32);  
  if(Process32First(hProcessSnap,&pe32))  
  {  
   do  
   {  
    if(nID==pe32.th32ProcessID) //判断制定进程号 
    {  
     strName.Format(L"进程编号%d的进程名为:%s",nID,pe32.szExeFile);  
     AfxMessageBox(strName);  
    }  
   }  
   while(Process32Next(hProcessSnap,&pe32));  
  }  
  else  
  {  
   ::MessageBox(NULL,L"出现意外错误!",L"错误提示",MB_OK);  

  return   FALSE;
  }  
  CloseHandle(hProcessSnap);

return   TRUE;

}

=======================================

获取句柄

=======================================

HANDLE hProcess=NULL;
 HANDLE hThread=NULL;

hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID);   //进程句柄
hThread = OpenThread(THREAD_ALL_ACCESS , FALSE, dwThreadID);        //线程句柄




你可能感兴趣的:(MFC)