Reputation: 121
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
Upvotes: 0
Views: 3027
Reputation: 121
<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();
}
Upvotes: 0
Reputation: 2938
Do it WPF style and use ApplicationCommands.Paste and make the textbox readonly.
Upvotes: 2
Reputation: 1550
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 = "";
}
}
Upvotes: 0
Reputation: 3018
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;
}
Upvotes: 1
Reputation: 2230
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.
Upvotes: 0