// File: OpenProgramOnTaskbar.h #pragma once #include <vector> struct TaskInfo { // 程序名称 CString strProgramName; // 窗口句柄 HWND hWnd; }; class TaskbarInfo { public: // 回调函数 static BOOL CALLBACK EnumWindowProc(HWND hWnd, LPARAM lParam); public: // 记录在任务栏打开的程序 std::vector<TaskInfo> m_TaskbarInfoArr; // 顶层窗口句柄 HWND m_hWnd; public: TaskbarInfo(); ~TaskbarInfo(); // 获得在任务栏打开程序信息 void GetTaskbarInof (void); // 获得顶层窗口句柄,失败返回NULL HWND GetTopWnd (void); };
// File: OpenProgramOnTaskbar.cpp #include "stdafx.h" // 如果编译出错,请删除这句 #include "OpenProgramOnTaskbar.h" #include "Psapi.h" #pragma comment(lib, "Psapi.lib") TaskbarInfo::TaskbarInfo() { } TaskbarInfo::~TaskbarInfo() { } void TaskbarInfo::GetTaskbarInof (void) { EnumWindows(EnumWindowProc, (LPARAM)this); } BOOL CALLBACK TaskbarInfo::EnumWindowProc(HWND hWnd, LPARAM lParam) { TaskbarInfo * pTaskbarInfo = (TaskbarInfo*)lParam; TCHAR szWindow[256]={0}; TaskInfo taskInfo; ::GetWindowText(hWnd, szWindow, 255); //获取窗口标题 if ( ::IsWindow(hWnd) && ::IsWindowVisible(hWnd) && (::GetWindowLong(hWnd, GWL_EXSTYLE)&WS_EX_TOOLWINDOW)!=WS_EX_TOOLWINDOW && ::GetWindowLong(hWnd, GWL_HWNDPARENT)==0 ) { DWORD dwPID; //保存进程标识符 GetWindowThreadProcessId(hWnd, &dwPID); //接受一个窗口句柄。dwPID保存窗口的创建者的进程标识符,GetWindowThreadProcessId返回值是该创建者的线程标识符 HANDLE hBrowser = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID); //打开一个已存在的进程对象,并返回进程的句柄,这就是我们要的进程句柄了 WCHAR exePath[256]; memset(exePath, 0, 256); //获取程序的path,并保存到exePath GetModuleFileNameEx(hBrowser, NULL, exePath, MAX_PATH); CString strTemp = exePath; strTemp.MakeLower(); // 过滤在桌面打开的文件夹等 if (!strTemp.IsEmpty() && strTemp.Find(_T("explorer.exe")) == -1) { taskInfo.strProgramName = szWindow; taskInfo.hWnd = hWnd; pTaskbarInfo->m_TaskbarInfoArr.push_back(taskInfo); memset(szWindow, 0, 256); } } return TRUE; } HWND TaskbarInfo::GetTopWnd (void) { DWORD dwPID; //保存进程标识符 HWND hWnd = NULL; hWnd = ::GetForegroundWindow(); GetWindowThreadProcessId(hWnd, &dwPID); //接受一个窗口句柄。dwPID保存窗口的创建者的进程标识符,GetWindowThreadProcessId返回值是该创建者的线程标识符 HANDLE hBrowser = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID); //打开一个已存在的进程对象,并返回进程的句柄,这就是我们要的进程句柄了 WCHAR exePath[256]; memset(exePath, 0, 256); //获取程序的path,并保存到exePath GetModuleFileNameEx(hBrowser, NULL, exePath, MAX_PATH); CString strTemp = exePath; strTemp.MakeLower(); if (!strTemp.IsEmpty() && strTemp.Find(_T("explorer.exe")) == -1) { m_hWnd = hWnd; if (m_hWnd != NULL) { return m_hWnd; } } return NULL; }