在vc++中获取活动进程名
Get active processname in vc++
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
是我程序中的一个参数。如果您在尝试此代码时遇到任何问题,请随时告诉我。
相关文章:
- Windows资源监视器使用哪些Win32函数来检测已终止进程的磁盘和网络活动
- 如何防止我的dll在某个进程未处于活动状态时运行
- 为什么名为互斥锁文档的加速间进程说每个进程都应该有自己的名称互斥锁?
- 在子进程处于活动状态时读取子进程的输出
- MFC - 主窗口/进程的随机名称和类名
- 如何使进程B仅在进程A处于活动状态时运行
- C++ 在进程杀死其父进程后保持进程活动状态
- 在父进程内启动子进程进程
- 如何使用JNI获取浏览器上当前活动选项卡的进程ID
- 从HWND获取图标进程,进程名或其他进程标识符
- 如何在winapi窗口中获得当前活动窗口的进程名?
- Windows 8/10中活动窗口的进程名
- 如何在不枚举进程的情况下,通过c++从进程id中获取进程名
- 如何检查进程是否关闭/活动
- 是否可以重命名进程类窗口名
- 在vc++中获取活动进程名
- 为什么OSX活动监视器不显示我启动的进程?
- 在Linux/ c++中,发送给线程/进程的信号是否使其变为活动状态?
- 从“进程名”中获取进程ID
- 从jni直接调用android活动从c++进程没有Java端