在vc++中获取活动进程名

Get active processname in vc++

本文关键字:活动进程 进程名 活动 获取 vc++      更新时间:2023-10-16

Am正在vc++中进行后台应用程序

我如何获得当前应用程序的进程名称,例如"Iexplore"用于使用Internet Explorer,"Skype"用于带有"Skype-username"的窗口,"Explorer"用于使用windows资源管理器?

我引用了这个链接,但得到了Null错误:http://www.codeproject.com/Articles/14843/Finding-module-name-from-the-window-handle

这可以使用以下代码完成:

bool GetActiveProcessName(TCHAR *buffer, DWORD cchLen)
{
    HWND fg = GetForegroundWindow();
    if (fg)
    {
        DWORD pid;
        GetWindowThreadProcessId(fg, &pid);
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
        if (hProcess)
        {
            BOOL ret = QueryFullProcessImageName(hProcess, 0, buffer, &cchLen);
            //here you can trim process name if necessary
            CloseHandle(hProcess);
            return (ret != FALSE);
        }
    }
    return false;
}

然后

TCHAR buffer[MAX_PATH];
if(GetActiveProcessName(buffer, MAX_PATH))
{
    _tprintf(_T("Active process: %sn"), buffer);
}
else
{
    _tprintf(_T("Cannot obtain active process name.n"));
}

请注意,QueryFullProcessImageName函数仅在Windows Vista之后可用,在早期的系统上,您可以使用GetProcessImageFileName(它类似,但需要与psapi.dll链接,并返回设备路径,而不是通常的win32路径)

基于一些研究,我在QT5/C++项目中使用了这段代码,成功地获得了当前活动的进程名称和窗口标题(感谢@dsi)。只是想分享代码,让其他人从中受益。

# Put this two declarations in the top of the CPP file
#include <windows.h>
#pragma comment(lib, "user32.lib")

并将以下内容放入一个方法中:

// get handle of currently active window
HWND hwnd = GetForegroundWindow();
if (hwnd) {
    // Get active app name
    DWORD maxPath = MAX_PATH;
    wchar_t app_path[MAX_PATH];
    DWORD pid;
    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
    if (hProcess) {
        QueryFullProcessImageName(hProcess, 0, app_path, &maxPath);
        // here you can trim process name if necessary
        CloseHandle(hProcess);
        QString appPath = QString::fromWCharArray(app_path).trimmed();
        QFileInfo appFileInfo(appPath);
        windowInfo.appName = appFileInfo.fileName();
    }
    // Get active window title
    wchar_t wnd_title[256];
    GetWindowText(hwnd, wnd_title, sizeof(wnd_title));
    windowInfo.windowTitle = QString::fromWCharArray(wnd_title);
}

这段代码可能不会直接编译,因为windowInfo是我程序中的一个参数。如果您在尝试此代码时遇到任何问题,请随时告诉我。