I'm trying to make a "keylogger"... well, it's not entirely a keylogger because it only displays the keystrokes and doesn't log them to a file. I was planning to use it on my Google+ Hangouts, so I can still show my keystrokes without having to use it with video recording software.
private void OnKeyDown(object sender, KeyEventArgs e)
{
lblText.Text = "";
lblText.Visible = false;
boxSpKey.Image = null;
boxSpKey.Visible = false;
boxCtrl.Visible = e.Control;
boxAlt.Visible = e.Alt;
boxWin.Visible = false;
boxShift.Visible = e.Shift;
Keys pKey = e.KeyData;
if (btnIcons.ContainsKey(pKey))
{
boxSpKey.Visible = true;
boxSpKey.Image = btnIcons[pKey];
}
// this part I haven't figured out either, but is irrelevant to my question.
}
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
lblText.Visible = true;
lblText.Text = ((char)e.KeyChar).ToString();
}
[Context: lblText is a label containing the key text, boxSpKey is a PictureBox for special keys such as ESC, for which I've made each one an icon. boxCtrl, boxAlt, boxWin and boxShift are also PictureBoxes are quite self-explanatory.]
Questions:
It seems that the values of
e.Control,e.Altande.Shiftare always False, so the respectivePictureBoxes wouldn't show up.How do I check for the status of the
Winkey? I would prefer not to use low-levelVK_*constants.When
OnKeyPresshandles the events, mostly with the use of the modifier keys, I get random characters... How exactly do I get the original key strokes from them? i.e. I want to getCtrl+Shift+Binstead of┐.
UPDATE: I've decided to go low-level with the modifier keys, so I used P/Invoke:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte[] lpKeyState);
public static byte code(Keys key)
{
return (byte)((int)key & 0xFF);
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
var array = new byte[256];
GetKeyboardState(array);
// ...
if ((array[code(Keys.ControlKey)] & 0x80) != 0)
boxCtrl.Visible = true;
if ((array[code(Keys.LMenu)] & 0x80) != 0 || (array[code(Keys.RMenu)] & 0x80) != 0)
boxAlt.Visible = true;
if ((array[code(Keys.LWin)] & 0x80) != 0 || (array[code(Keys.RWin)] & 0x80) != 0)
boxWin.Visible = true;
if ((array[code(Keys.ShiftKey)] & 0x80) != 0)
boxShift.Visible = true;
// ...
}
The good news is that I got the Ctrl, Win and Shift keys working, but not Alt; unless Alt ≠ LMenu and RMenu. What gives?
should map to either
Altkey on my keyboard results in aKeyCodevalue ofKeys.Menuin my handler. It doesn't seem to distinguish between left and right. Unfortunately, I don't have another keyboard to test with.LMenuandRMenuare supposed to check for theAltkeys on either side, but it seems that simplyKeys.Menuworks. Thanks~