0

Im trying to open process using Wisual Studio 2012, c++ console application and get 87 error:

#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. i get the pid correctly

Evgeniy
  • 1,535
  • 1
  • 10
  • 9
  • I assume the error is located on `HANDLE proc = ...` is this correct? The following question's answer might be helpful: http://stackoverflow.com/questions/4988082/openprocess-error-87-invalid-parameter If I were to hazard an educated guess the reason for this error is because of the `PROCESS_ALL_ACCESS` based on the documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx What operating system was your applicatin compiled on and what operating system is it running on? – Security Hound May 23 '13 at 12:50
  • Do you actually check the handle you get back before checking for an error? If you got a valid handle then the value from `GetLastError` is meaningless. – Retired Ninja May 23 '13 at 12:56
  • @user2387336 - Furthermore `OpenProcess` returns this error when the pid is invalid, so that could also be the problem, despite you thinking you got the pid correctly. – Security Hound May 23 '13 at 12:57

1 Answers1

1

The function GetWindowThreadProcessId returns the id of the thread that created the window.

You need to use the corresponding process id, which is returned in the second argument. So something like this

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;
}

Also, you should really be checking that FindWindow has succeeded and if you do get a valid HANDLE you must remember to CloseHandle when you've finished with it.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113