I have TextBox in WPF where i need to fill the box only by pasting (ctrl +v) not by typing. So i need to restrict entire key press except ctrl+v. Since WPF is not having keypress event i am facing the problem to restrict the keypress
- Well, I have not actually tried this out, but perhaps you could set a "key press" handler that will check the length of the input string. So If(input.length() > 1) // accept the input else // input = "";Hooplator15– Hooplator152015-09-10 11:27:33 +00:00Commented Sep 10, 2015 at 11:27
- @JohnAugust what if he pastes only 1 character at a time?Kryptonian– Kryptonian2015-09-10 11:29:49 +00:00Commented Sep 10, 2015 at 11:29
- thank you bro but if i paste the content then the length will increase and it will restrict the contentjeevan_jk– jeevan_jk2015-09-10 11:30:15 +00:00Commented Sep 10, 2015 at 11:30
- ...Ahh, yes, all very good points, especially if only one character is pasted. In that case have a look at the "modifiers" property: stackoverflow.com/questions/25135505/… Then add that into the if statement check. So in other words, if you see if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) Then accept the input, else input = "";Hooplator15– Hooplator152015-09-10 11:38:23 +00:00Commented Sep 10, 2015 at 11:38
Add a comment |
5 Answers
you can add this Key_Down handler to the textBox:
private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Modifiers == Keys.Control && e.Key==Key.V) { //Logic here } else e.handled=true; } 1 Comment
nguyenmanh02123221
here is wpf not winform
Provided you don't allow Right Click + Paste, but only Ctrl + V, I would simply check for the Ctrl key modifier being pressed and prevent everything else.
1 Comment
Wouter
Do it WPF style and use ApplicationCommands.Paste and make the textbox readonly.
<TextBox IsReadOnly="True" Name="Policy_text"> <TextBox.CommandBindings> <CommandBinding Command="ApplicationCommands.Paste" CanExecute="PasteCommand_CanExecute" Executed="PasteCommand_Executed" /> </TextBox.CommandBindings> </Textbox> and in code behind
private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = Clipboard.ContainsText(); } private void PasteCommand_Executed(object sender, ExecutedRoutedEventArgs e) { Policy_text.Paste(); }