Skip to content

Instantly share code, notes, and snippets.

@michel-pi
Created September 30, 2018 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michel-pi/777ebc70d5bf0fbdcb22e9e26b1bc0fb to your computer and use it in GitHub Desktop.
Save michel-pi/777ebc70d5bf0fbdcb22e9e26b1bc0fb to your computer and use it in GitHub Desktop.
Retreives a buffer containing all keys state
using System;
using System.Runtime.InteropServices;
namespace System.Input
{
public class KeyboardState
{
[DllImport("user32.dll")]
private static extern int GetKeyboardState(byte[] buffer);
[DllImport("user32.dll")]
private static extern short GetKeyState(int key);
public static readonly int MaxKeyCode = 0xFF;
public static readonly int MinKeyCode = 0x00;
private byte[] _buffer;
public byte this[int index]
{
get
{
if (index < MinKeyCode || index >= MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(index));
return _buffer[index];
}
}
public byte this[VirtualKeyCode virtualKeyCode]
{
get
{
return this[(int)virtualKeyCode];
}
}
public KeyboardState()
{
_buffer = new byte[MaxKeyCode];
Update();
}
public bool IsPressed(int index)
{
if (index < MinKeyCode || index >= MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(index));
// a key is pressed when it's least significant bit is set
return (_buffer[index] & (1 << 7)) != 0;
}
public bool IsPressed(VirtualKeyCode virtualKeyCode)
{
int index = (int)virtualKeyCode;
if (index < MinKeyCode || index >= MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(index));
return (_buffer[index] & (1 << 7)) != 0;
}
public bool IsToggled(int index)
{
if (index < MinKeyCode || index >= MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(index));
// a key is pressed when it's most significant bit is set
return (_buffer[index] & (1 << 0)) != 0;
}
public bool IsToggled(VirtualKeyCode virtualKeyCode)
{
int index = (int)virtualKeyCode;
if (index < MinKeyCode || index >= MaxKeyCode) throw new ArgumentOutOfRangeException(nameof(index));
return (_buffer[index] & (1 << 0)) != 0;
}
public void Update()
{
// invalidates this thread keyboardstate when not called from an ui thread
GetKeyState(0);
GetKeyboardState(_buffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment