I'd like to locally hook my WindowProc function. First I was thinking of SetWindowsHookEx, but I wouldn't like to have an external DLL only for this hook. I'd like to make it internally and locally (I don't want a global hook). That's why I came across with SetWindowsLong. I'm trying to change the WindowProc with the GWL_WNDPROC option, however I always get error: Access Denied and I've got no idea why. Here's my very simple example which is sadly not working:
#include <windows.h>
#include <stdio.h>
WNDPROC pOrigProc;
LRESULT CALLBACK HookWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
printf("Message arrived!\n");
return CallWindowProc(pOrigProc, hwnd, uMsg, wParam, lParam);
}
int main()
{
HWND handle = FindWindow("ConsoleWindowClass", 0);
if(!handle)
{
printf("HWND get error!\n");
}
else
{
DWORD dwProcId;
GetWindowThreadProcessId(handle, &dwProcId);
if( dwProcId != GetCurrentProcessId())
{
printf("Corrupted Handle!\n");
}
else
{
printf("Window handle belongs to my process!\n");
}
}
pOrigProc = (WNDPROC)SetWindowLong(handle, GWL_WNDPROC, (LONG)HookWndProc);
if(!pOrigProc)
{
printf("SWL Error: %d\n", GetLastError());
}
else
{
printf("Successfully hooked the Window Callback!\n");
}
MSG message; // Let's start imitating the prescence of a Win32GUI
while (GetMessage(&message, NULL, 0, 0))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
}
Of course FindWindow is not going to be the best solution in my main project, but I think it's good enough in this small example. As you can see I'm making sure that the found HWND is my own, so it shouldn't be the problem.
In my case it's returning "Window handle belongs to my process!" and SWL Error: 5
Error 5 is (according to msdn) ACCESS DENIED.
I hope someone can see that possible small stupid mistake which I can't find. Thank you!
MSDN says "You cannot change this attribute if the window does not belong to the same process as the calling thread". From your example is visible that your app is console, not GUI. And probably the ConsoleWindowClass
is not defined by your app but globally by Windows. Try similar but with GUI project.