As I do I take the handle of the active window with the GetForegroundWindow() function, I need to find out the name of the process using this WinAPI for this handle.
How can I do that?
You can simply and briefly:
#include <iostream> #include <windows.h> #include <psapi.h> int main() { Sleep(1000); // Чтобы успеть переключиться в другое окошко :) DWORD pid; GetWindowThreadProcessId(GetForegroundWindow(),&pid); HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); char name[256]; if (GetProcessImageFileName(hProc,name,256)) std::cout << name << std::endl; CloseHandle(hProc); } #pragma comment(lib,"user32") First get the process id that owns the active window: GetWindowThreadProcessId() .
Then get the handle (handle, handle) of the process using OpenProcess() . When opening a process, it is sufficient to indicate the right to PROCESS_QUERY_INFORMATION - obtaining limited information about the process.
Finally, extract the process name from the handle: GetProcessImageFileName() .
This feature is available starting with Windows XP. For earlier versions of the OS, you must use GetModuleFilenameEx() , but then the process access rights must be PROCESS_QUERY_INFORMATION | PROCESS_VM_READ PROCESS_QUERY_INFORMATION | PROCESS_VM_READ .
Why didn't I replace steps 1 and 2 with the call to the GetProcessHandleFromHwnd() function? The fact is that this function tries to open a process with an excessive set of privileges, which the user may not have. For example, PROCESS_VM_READ (reading other people's memory) is not applicable to processes that are not running under the current user (if the current user is not an administrator).
Summary Code:
#include <iostream> #include <string> #include <windows.h> #include <psapi.h> std::string getForegroundWindowProcessName() { const HWND hForeground = GetForegroundWindow(); if(hForeground) { DWORD dwPID = 0; GetWindowThreadProcessId(hForeground, &dwPID); const HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPID); if(hProc) { TCHAR szPath[MAX_PATH]; GetProcessImageFileName(hProc, szPath, sizeof(szPath)); CloseHandle(hProc); // Пытаемся извлечь имя файла. Если GetProcessImageFileName по каким-то // причинам предоставил не путь, а просто имя, возвращаем именно его. TCHAR szTitle[MAX_PATH]; if(GetFileTitle(szPath, szTitle, sizeof(szTitle)) == 0) return std::string(szTitle); else return std::string(szPath); } else // Ошибка при открытии процесса. За подробностями — к GetLastError() return std::string(); } else // Ни одно окно не выделено return std::string(); } int main() { std::cout << getForegroundWindowProcessName(); } The answer is taken from here.
#include <cstdio> #include <windows.h> #include <tlhelp32.h> int main( int, char *[] ) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } If you want to use PROCESS_ALL_ACCESS in an open process, use this code.
#include <cstdio> #include <windows.h> #include <tlhelp32.h> void EnableDebugPriv() { HANDLE hToken; LUID luid; TOKEN_PRIVILEGES tkp; OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = luid; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL); CloseHandle(hToken); } int main( int, char *[] ) { EnableDebugPriv(); PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, "target.exe") == 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); // Do stuff.. CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } Source: https://ru.stackoverflow.com/questions/614789/
All Articles