I want to get the keys pressed on the keyboard either with or without caplock:
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e
The best way to handle this is by using Window_TextInput event rather than KeyDown.
But as you said this event does not fire on your application you can rather use a hack like this :
bool iscapsLock = false;
bool isShift = false;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.CapsLock)
iscapsLock = !iscapsLock;
if (e.Key >= Key.A && e.Key <= Key.Z)
{
bool shift = isShift;
if (iscapsLock)
shift = !shift;
int s = e.Key.ToString()[0];
if (!shift)
{
s += 32;
}
Debug.Write((char)s);
}
}
This will properly print the characters based on whether capslock is turned on or not. The initial value of the Capslock can be retrieved using this link :
http://cboard.cprogramming.com/csharp-programming/105103-how-detect-capslock-csharp.html
I hope this works for you.
Overriding TextInput/PreviewTextInput (or listening to the events) should work.
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
base.OnPreviewTextInput(e);
Console.WriteLine(e.Text);
}
You can check in your KeyDown
event whether CAPS lock
is on or off using Control.IsKeyLocked method. Also, you might need to check if user typed in capital using Shift
key which can be identified using Modifiers
enum like this -
private void Window_KeyDown(object sender, KeyEventArgs e)
{
string key = e.Key.ToString();
bool isCapsLockOn = System.Windows.Forms.Control
.IsKeyLocked(System.Windows.Forms.Keys.CapsLock);
bool isShiftKeyPressed = (Keyboard.Modifiers & ModifierKeys.Shift)
== ModifierKeys.Shift;
if (!isCapsLockOn && !isShiftKeyPressed)
{
key = key.ToLower();
}
}
You can't use the KeyDown
event. You'll need to use the TextInput
event. This will print the original letter with it's caption (Uppercase/Lowercase).
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
Console.WriteLine(e.Text);
}
Now, this will also print the Shift and so on if it's pressed. If you don't want those modifiers just get the last item of the string -treat it as a char array ;)-
KeyEventArgs class has "Shift" field which indicating whether the SHIFT key was pressed.
Otherwise, because Window_KeyDown method will be called when CAPS_LOCK pressed, you can save a bool value indicating whether the CAPS_LOCK key was pressed.
bool isCapsLockPressed;
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
if(e.KeyCode == Keys.CapsLock) {
isCapsLockPressed = !isCapsLockPressed;
}
}