I wan't to disable all default shortcuts in WPF TextBox. Shortcuts like Ctrl+A, Ctrl+V, Ctrl+C etc. Can this be done?. It looks to me that these shortcuts are executed before KeyDown event
+2
A:
You can intercept the keystrokes in the PreviewKeyDown event. Set the e.Handled member to true and that will prevent the actually processing of the keys.
JaredPar
2009-03-22 15:29:20
Thanks. That's right to the point. Never seen this preview event before
Sergej Andrejev
2009-03-22 15:34:29
That'll only work for keystrokes. What if the command is invoked via the context menu? Or the application menu?
Kent Boogaart
2009-03-22 15:35:37
@Kent, I *believe* that goes through WPF commands. I am very unfamiliar with their implementation and cannot provide any useful comments on how that would work. Although I'd love to see someone do so.
JaredPar
2009-03-22 15:36:45
@Jared: Your method prevents an input binding from invoking the command, but there are other ways to execute the command. Anyways, it's not exactly clear whether the OP wants to disable the *commands* altogether or just the *keystrokes* to invoke the commands.
Kent Boogaart
2009-03-22 15:39:20
The InputBinding's should be updated to use ApplicationCommands.NotACommand to disable them.
sixlettervariables
2009-06-15 19:00:17
+2
A:
public Window1()
{
InitializeComponent();
CommandManager.AddPreviewCanExecuteHandler(_textBox, _canExecute);
}
private void _canExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
The above will prevent the TextBox from saying it can handle any command. You can selectively choose which commands you want to disable by examining the EventArgs
. Or you can do this in XAML:
<TextBox x:Name="_textBox">
<TextBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Copy" CanExecute="_canExecute"/>
</TextBox.CommandBindings>
</TextBox>
Here we're just disabling the execution of the Copy command. Control-C won't work, nor will the context menu or main menu. In fact, any control that executes the Copy command will be disabled if the focus is in the TextBox
.
HTH, Kent
Kent Boogaart
2009-03-22 15:34:50