tags:

views:

712

answers:

2

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
Thanks. That's right to the point. Never seen this preview event before
Sergej Andrejev
That'll only work for keystrokes. What if the command is invoked via the context menu? Or the application menu?
Kent Boogaart
@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
@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
The InputBinding's should be updated to use ApplicationCommands.NotACommand to disable them.
sixlettervariables
+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