I'm trying a way to catch keys combination from a TextBox in a WPF application. The code written so far (that i found in an other discussion) helps me to do this, except for those combinations that are linked to a shortcut command (Ctrl+C, Ctrl+V, Ctrl+X...). I want to catch all keys that user press on textbox (Space, Delete, Backspace and all the combinations above). This is the code:
int MaxKeyCount = 3;
List<Key> PressedKeys = new List<Key>();
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Handled) return;
//Check all previous keys to see if they are still pressed
List<Key> KeysToRemove = new List<Key>();
foreach (Key k in PressedKeys)
{
if (!Keyboard.IsKeyDown(k))
KeysToRemove.Add(k);
}
//Remove all not pressed keys
foreach (Key k in KeysToRemove)
PressedKeys.Remove(k);
//Add the key if max count is not reached
if (PressedKeys.Count < MaxKeyCount)
//Add the key if it is part of the allowed keys
//if (AllowedKeys.Contains(e.Key))
if (!PressedKeys.Contains(e.Key))
PressedKeys.Add(e.Key);
PrintKeys();
e.Handled = true;
}
private void PrintKeys()
{
//Print all pressed keys
string s = "";
if (PressedKeys.Count == 0) return;
foreach (Key k in PressedKeys)
if (IsModifierKey(k))
s += GetModifierKey(k) + " + ";
else
s += k + " + ";
s = s.Substring(0, s.Length - 3);
TextBox.Text = s;
}
private bool IsModifierKey(Key k)
{
if (k == Key.LeftCtrl || k == Key.RightCtrl ||
k == Key.LeftShift || k == Key.RightShift ||
k == Key.LeftAlt || k == Key.RightAlt ||
k == Key.LWin || k == Key.RWin)
return true;
else
return false;
}
private ModifierKeys GetModifierKey(Key k)
{
if (k == Key.LeftCtrl || k == Key.RightCtrl)
return ModifierKeys.Control;
if (k == Key.LeftShift || k == Key.RightShift)
return ModifierKeys.Shift;
if (k == Key.LeftAlt || k == Key.RightAlt)
return ModifierKeys.Alt;
if (k == Key.LWin || k == Key.RWin)
return ModifierKeys.Windows;
return ModifierKeys.None;
}
Someone has an idea for disable shortcut commands, keeping keystrokes? Thanks!
I think those can be overridden using custom CommandBindings
using the corresponding application commands. Set ExecutedRoutedEventArgs.Handled
to true
in the handler.
Also: This is a bad idea in terms of usability.
Example:
<TextBox>
<TextBox.CommandBindings>
<CommandBinding Command="Paste" Executed="CommandBinding_Executed"/>
</TextBox.CommandBindings>
</TextBox>
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
e.Handled = true;
}