Created
September 30, 2018 23:21
-
-
Save michel-pi/777ebc70d5bf0fbdcb22e9e26b1bc0fb to your computer and use it in GitHub Desktop.
Retreives a buffer containing all keys state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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