码迷,mamicode.com
首页 > 编程语言 > 详细

C++获取进程号及窗口

时间:2015-03-05 18:59:04      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

#include <TlHelp32.h>

//根据进程名获取进程ID
BOOL GetPidByProcessName(TCHAR *pProcess, DWORD*dwPid) 
{ 
    HANDLE hSnapshot; 
    PROCESSENTRY32 lppe; 
    //创建系统快照 
    hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); 

    if (hSnapshot == NULL) 
        return FALSE; 

    //初始化 lppe 的大小 
    lppe.dwSize = sizeof(lppe); 

    //查找第一个进程 
    if (!::Process32First(hSnapshot, &lppe))
        return FALSE; 
    do 
    { 
        if(_tcscmp(lppe.szExeFile, pProcess) == 0)
        { 
            *dwPid =  lppe.th32ProcessID;
        }   
    } 
    while (::Process32Next(hSnapshot, &lppe)); //查找下一个进程  

    return TRUE;
}

//根据进程ID获取窗口句柄
HWND GetHwndByPid(DWORD dwProcessID)
{
    //返回Z序顶部的窗口句柄
    HWND hWnd = ::GetTopWindow(0);

    while ( hWnd )
    {
        DWORD pid = 0;
        //根据窗口句柄获取进程ID
        DWORD dwTheardId = ::GetWindowThreadProcessId( hWnd,&pid);

        if (dwTheardId != 0)
        {
            if ( pid == dwProcessID )
            {
                return hWnd;
            }
        }
        //返回z序中的前一个或后一个窗口的句柄
        hWnd = ::GetNextWindow(hWnd , GW_HWNDNEXT);

    }
    return hWnd;
}
 
 
 

typedef struct
{
 HWND hWnd;
 DWORD dwPid;
}WNDINFO;
 
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
 WNDINFO* pInfo = (WNDINFO*)lParam;
 DWORD dwProcessId = 0;
 GetWindowThreadProcessId(hWnd, &dwProcessId);
 
 if(dwProcessId == pInfo->dwPid)
 {
  pInfo->hWnd = hWnd;
  return FALSE;
 }
 return TRUE;
}
 
HWND GetHwndByProcessId(DWORD dwProcessId)
{
 WNDINFO info = {0};
 info.hWnd = NULL;
 info.dwPid = dwProcessId;
 EnumWindows(EnumWindowsProc, (LPARAM)&info);
 return info.hWnd;
}

C++获取进程号及窗口

标签:

原文地址:http://www.cnblogs.com/liangxiaofeng/p/4316109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!