0

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

4
  • 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 = ""; Commented Sep 10, 2015 at 11:27
  • @JohnAugust what if he pastes only 1 character at a time? Commented 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 content Commented 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 = ""; Commented Sep 10, 2015 at 11:38

5 Answers 5

2

Do it WPF style and use ApplicationCommands.Paste and make the textbox readonly.

Sign up to request clarification or add additional context in comments.

2 Comments

@jeevan_jk try and come back for help... it's not nice to have people code for you.
@Wouter Thank you much i have implemented it
1

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

here is wpf not winform
0

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

Do it WPF style and use ApplicationCommands.Paste and make the textbox readonly.
0

So try this:

 myTextBox.KeyDown += new KeyEventHandler(myTextBox_KeyDown); private void myTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) { input = myTextBox.Text; } else { input = ""; } } 

Comments

0
<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(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.