Keyboard hook in C++

Posts 1–15 of 16 · Page 1 of 2
Keyboard hook in C++
Apparently this is too hard for a lot of people to figure out so here's a little something to get them on their way...

Code:
// Keyhook.cpp : Defines the entry point for the console application.
// by B1ackAnge1
// Alt-F12 Exits app
// All you leechers have to do is parse the vkCode ;)
#include "stdafx.h"
using namespace std;

HHOOK hHook;

LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam, LPARAM lParam)
{
	if(wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
	{	
		PKBDLLHOOKSTRUCT pKey = (PKBDLLHOOKSTRUCT)lParam;
                //Now just check pKey->vkCode etc for whatever you want
                //for instance, a basic printout of the value and a check for pgup
		cout << pKey->vkCode << " ";
		if(pKey->vkCode == VK_PRIOR)
			cout << endl << "Page Up!" << endl;
	}
	CallNextHookEx(hHook,nCode,wParam,lParam);
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	RegisterHotKey(NULL,0xB1AC7B1A,MOD_ALT,VK_F12);
	HMODULE hInstance = GetModuleHandle(NULL);
	hHook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,hInstance,NULL);
	MSG msg;
	GetMessage(&msg,NULL,NULL,NULL);
	UnhookWindowsHookEx(hHook);
	return 0;
}
Figured i'd show what's in STDAFX.H since people will freak out when their copy/paste job doesn't compile...
Code:
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <iostream>
Oh and look.. not in a DLL

How's this not easy? XD

If you guys want though I can comment the code some more..
Quote Originally Posted by B1ackAnge1 View Post
Apparently this is too hard for a lot of people to figure out so here's a little something to get them on their way...

Code:
// Keyhook.cpp : Defines the entry point for the console application.
// by B1ackAnge1
// Alt-F12 Exits app
// All you leechers have to do is parse the vkCode ;)
#include "stdafx.h"
using namespace std;

HHOOK hHook;

LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam, LPARAM lParam)
{
	if(wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
	{	
		PKBDLLHOOKSTRUCT pKey = (PKBDLLHOOKSTRUCT)lParam;
                //Now just check pKey->vkCode etc for whatever you want
                //for instance, a basic printout of the value and a check for pgup
		cout << pKey->vkCode << " ";
		if(pKey->vkCode == VK_PRIOR)
			cout << endl << "Page Up!" << endl;
	}
	CallNextHookEx(hHook,nCode,wParam,lParam);
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	RegisterHotKey(NULL,0xB1AC7B1A,MOD_ALT,VK_F12);
	HMODULE hInstance = GetModuleHandle(NULL);
	hHook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,hInstance,NULL);
	MSG msg;
	GetMessage(&msg,NULL,NULL,NULL);
	UnhookWindowsHookEx(hHook);
	return 0;
}
Figured i'd show what's in STDAFX.H since people will freak out when their copy/paste job doesn't compile...
Code:
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <iostream>
Oh and look.. not in a DLL

How's this not easy? XD

If you guys want though I can comment the code some more..

Nothing at all to do with learning, but did you just think that up off top? o_o Or do you have this stuff saved away to help people?

Also, if you thought of that off top. <_< Wow. You type code really fast.
That was actually surprisingly less code then I expected. Thanks for this BA. :P

@ilovecookies: Some of the stuff is just standard windows code, the whole windows programming thing doesn't shock me as much as it used to. Not that it wouldn't have taken me 5 days to figure it out and shooting BA a instant message every 5min , but I imagine that's how it should look. If I ever saw a windows hook...
lol well it' s only a couple of function calls so to bang that out takes no time at all.. already wrote something similar a while ago in assembly so it was still fresh in memory (unlike a million other things haha)
And i'm a software engineer for a living so cranking out code is what I do all day lol

And yeah not much code/complexity involved with this at all really..
The core is the callback (which I filled with junk) and the call to register the hook.. so I could condence it even further down. The GetMessage in combination with the hotkey registration is a nice solution to avoid a while(true) loop and are not really part of the hooking

Really all it is is
Code:
//Initialize the hook
HMODULE hInstance = GetModuleHandle(NULL);
hHook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,hInstance,NULL);

//When exiting:
UnhookWindowsHookEx(hHook);


and then the actual hook
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam, LPARAM lParam)
Quote Originally Posted by B1ackAnge1 View Post
Really all it is is
Code:
//Initialize the hook
HMODULE hInstance = GetModuleHandle(NULL);
hHook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,hInstance,NULL);

//When exiting:
UnhookWindowsHookEx(hHook);


and then the actual hook
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam, LPARAM lParam)
Lol. Actually I just remembered I had some leeched source for a global Keyboard Hook laying around... kind of late now, but:
[php]
//http://qsoft.********
//For any questions/comments/thing send an email to arkon@ragestorm.com
//Feel free to do with this anything you want!
//21/4/2001

#include <windows.h>

#pragma data_seg("SharedBlock")
HHOOK hhook = NULL;
unsigned long keystrokes = 0;
int pcount = 0;
#pragma data_seg()

HINSTANCE g_hInstance = NULL;

_declspec(dllexport) LRESULT CALLBACK KBHookProc(int Code, WPARAM wParam, LPARAM lParam)
{
if (Code < 0) return(CallNextHookEx(hhook, Code, wParam, lParam));

if (lParam & (1 << 31)) keystrokes++;

return(CallNextHookEx(hhook, Code, wParam, lParam));
}

_declspec(dllexport) void SetKBHook()
{
if (!hhook) hhook = SetWindowsHookEx(WH_KEYBOARD, KBHookProc, g_hInstance, 0);
}

_declspec(dllexport) unsigned long GetKeyStrokes()
{
return(keystrokes);
}

_declspec(dllexport) void KillKBHook()
{
if(hhook) UnhookWindowsHookEx(hhook);
}

BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
if(pcount == 0)
{
// Init
g_hInstance = hInstance;
}
pcount++;
}
else if (dwReason == DLL_PROCESS_DETACH)
{
if(pcount == 1)
{
// Free
}
pcount--;
}
return(1);
}
[/php]
Woa, I've been waiting for this topic.

Too bad it's a little late, I got most of the info already. -.-
I always enjoyed never calling the next hook to mess with ppl
<('¯\__/|
...\____/
Note to why: STICKY o__O
Quote Originally Posted by TehKiller View Post
Note to why: STICKY o__O
Oh. Hey your back!

Wait... oh I guess I could do that.... hmmmm, but there are so many sticky's. I got an idea.
Is there a way to simulate key strokes using this kind of hook?
Quote Originally Posted by Void View Post
Is there a way to simulate key strokes using this kind of hook?
That's what I was wondering. I need it to press space and why said to check this out.
I don't need it for anything specific, I was just informed that PostMessage was slow and this is a better way to simulate keystrokes.
You're probably better off getting a pointer to the DirectInput keyboard device by hooking IDirectInput(Version)::CreateDevice, this might not be thread safe which could cause some synchonization issues you would have to work around(you could try creating your own devices, though this sometimes doesn't work depending how the first device was created). Mind you, if you have a hook on the API used to create it, you can always alter how the device was created to allow multiple input devices to recieve input.

@Davidmm, most game engines(at least mine) completely ignore keystrokes recived from the callback, instead they use game libraries such as DirectInput which is an interface to the actual device drivers managing devices such as they keyboard and mouse, bypassing the slow callback. Provided the target is using DirectInput, there are APIs that can be hooked to simulate key-presses. If they're using another library for input you will have to do more research on that library.
Yeh, hooking DirectInput is hands down the best way, but some games have hack protections, so you can't directly hook the Input Device without a bunch of sirens going off. right? And ofcourse you would have to hook the Input devices. I have no idea how to go about that... since you would need some kind of pointer to the device. =/
Posts 1–15 of 16 · Page 1 of 2
This thread is closed for replies.

Similar Threads

Tags for this Thread

Need help?