How can I make a WPF textbox cut, copy and paste restricted?
Asked
Active
Viewed 3.1k times
34
-
I dont know much about WPF. You could use a label instead (that will not let you do a cut/copy/paste. – shahkalpesh Jun 02 '09 at 06:57
-
5But I want the user to input data through keyboard. – Sauron Jun 02 '09 at 07:01
2 Answers
53
Cut, Copy and Paste are the common commands used any application,
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"
ContextMenu="{x:Null}" />
in above textbox code we can restrict these commands in PrviewExecuted event of CommandManager Class
and in code behind add below code and your job is done
private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Copy ||
e.Command == ApplicationCommands.Cut ||
e.Command == ApplicationCommands.Paste)
{
e.Handled = true;
}
}

Athari
- 33,702
- 16
- 105
- 146

Prashant Cholachagudda
- 13,012
- 23
- 97
- 162
-
4
-
-
1I suggest for anyone to use it in the following form: `e.Command == ApplicationCommands.Cut`, instead of casting and relying on a string that might change due to localization. I submitted an edit suggestion to Prashant. – VitalyB Sep 27 '11 at 15:38
-
I am facing the same problem in my windows phone app 8.1. There is no CommandManager in windows phone application..can anyone help? – Tasnim Fabiha Feb 26 '17 at 10:23
19
The commandName method will not work on a System with Japanese OS as the commandName=="Paste" comparision will fail. I tried the following approach and it worked for me. Also I do not need to disable the context menu manually.
In the XaML file:
<PasswordBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
CanExecute="CommandBinding_CanExecutePaste"></CommandBinding>
</PasswordBox.CommandBindings>
In the code behind:
private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}

Martin Brown
- 24,692
- 14
- 77
- 122

Debashis Panda
- 332
- 2
- 4
-
I used this code and it works great when you press `Ctr+V`. I noticed though that when you right click the password box, this function gets called in some sort of infinite loop. (If you add a msgbox to this function you can see that). How can that be prevented? – yem Mar 30 '22 at 11:40