本文介绍了通过图像名称获取进程的进程句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Win32通过它的可执行文件名获得另一个进程的进程手柄需要从C最简单的方法。

I need the simplest way from C using Win32 to get the process handle of another process by its executable file name.

我要寻找的过程中没有任何注册窗口类。我也知道,如果正在运行将会有只有一个它运行的实例。

The process I am looking for does not have any registered window classes. I also know that if it is running there will be only one instance of it running.

推荐答案

使用的,和枚举所有的处理。

Use CreateToolhelp32Snapshot, Process32First, and Process32Next to enumerate all of the processes.

在你可以找到一个 szExeFile 成员。
你可以通过调用获得进程句柄与进程ID th32ProcessID 同一结构中。

Inside the PROCESSENTRY32 you can find a szExeFile member.You can get the process handle by calling OpenProcess with the process ID th32ProcessID within the same struct.

一旦你找到符合您的exe名称的进程,你可以打破你的循环,获得句柄。

Once you find a process matching your exe name, you can break out of your loop and obtain the handle.

请注意:如果您需要枚举每一个过程无论会话是什么,你应该获得SE_DEBUG特权。

Note: If you need to enumerate EVERY process no matter what the session is, you should acquire the SE_DEBUG privilege.

在你的主电话的顶部这样的:

At the top of your main call this:

acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege

和这里的定义 acquirePrivilegeByName

BOOL acquirePrivilegeByName(
                            const TCHAR     *szPrivilegeName)
{
    HANDLE          htoken;
    TOKEN_PRIVILEGES    tkp;
    DWORD           dwerr;

    if (szPrivilegeName == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid)))
        return FALSE;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken))
        return FALSE;

    if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) ||
        GetLastError() != ERROR_SUCCESS)    // may equal ERROR_NOT_ALL_ASSIGNED
    {
        dwerr = GetLastError();
        CloseHandle(htoken);
        SetLastError(dwerr);
        return FALSE;
    }

    CloseHandle(htoken);
    SetLastError(ERROR_SUCCESS);

    return TRUE;
} //acquirePrivilegeByName()

除了我上面说的,有关于如何使用上面的Win32 API here.

这篇关于通过图像名称获取进程的进程句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:47
查看更多