how can i forbid the copy/paste option of a textbox in vb.Net?

1.5k Views Asked by At

I have a textbox that is managed by the keyDown event which limits insertion 4 characters but when the user makes a copy / paste it DePace 4 character! So is that it is possible to prohibit this option.

thank you in advance

1

There are 1 best solutions below

1
On BEST ANSWER
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"/>

C#

private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
    if (e.Command == ApplicationCommands.Copy ||
        e.Command == ApplicationCommands.Cut  ||
        e.Command == ApplicationCommands.Paste)
    {
        e.Handled = true;
    }
}

VB.NET

Private Sub textBox_PreviewExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
    If e.Command Is ApplicationCommands.Copy 
         OrElse e.Command Is ApplicationCommands.Cut 
         OrElse e.Command Is ApplicationCommands.Paste Then
        e.Handled = True
    End If
End Sub

To Disable using Keys as(Ctrl+C,Ctrl+V) use following code:

C#

DataObject.AddPastingHandler(control, this.OnCancelCommand);
DataObject.AddCopyingHandler(control, this.OnCancelCommand);

private void OnCancelCommand(object sender, DataObjectEventArgs e)
{
    e.CancelCommand();
}

VB.NET

DataObject.AddPastingHandler(control, AddressOf Me.OnCancelCommand)
DataObject.AddCopyingHandler(control, AddressOf Me.OnCancelCommand)

private void OnCancelCommand(Object sender, DataObjectEventArgs e)
    e.CancelCommand()