WinApi OpenProcess错误87

时间:2013-05-23 12:48:12

标签: c++ winapi

我尝试使用Visual Studio 2012,c ++控制台应用程序打开进程并获得87错误:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int setLastObject(LPCWSTR wname) {
    LPCWSTR str = _TEXT("Name of window");
    HWND wnd = FindWindow(NULL,wname);

    LPDWORD cpid = 0;
    DWORD pid = GetWindowThreadProcessId(wnd,cpid);

    HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS,false,pid);
    int err = GetLastError();
    return err;
}

P.S。我正确地得到了pid

1 个答案:

答案 0 :(得分:1)

函数GetWindowThreadProcessId返回创建窗口的线程的id。

您需要使用相应的进程ID,该ID在第二个参数中返回。像这样的东西

EXTERN_DLL_EXPORT int setLastObject(LPCWSTR wname) {
    LPCWSTR str = _TEXT("Name of window");
    HWND wnd = FindWindow(NULL,wname);

    DWORD dwProcessId = 0;
    DWORD dwThreadId = GetWindowThreadProcessId(wnd, &dwProcessId);

    HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS,false,dwProcessId);
    int err = GetLastError();
    return err;
}

此外,您应该检查FindWindow是否已成功,如果您 获得有效HANDLE,您必须记得CloseHandle完成它。