Sagar0921 Sagar0921 - 1 year ago 82 Question

Let user copy and paste text in Text Box but disable manual Editing in C#

I am trying to create TextBox so that user can not type anything but they should be able to paste information using clip board text.

Answer Source

You can subscribe to the TextBox's KeyPress event in which you always set the e.Handled property to True. This will cause any keyboard input to not be handled by the TextBox itself, thus it won't add any characters unless you paste.

Dim InputIsCommand As Boolean = False

Private Sub TextBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.Control = True AndAlso (e.KeyCode = Keys.V OrElse e.KeyCode = Keys.C) Then
        InputIsCommand = True
    End If
End Sub

Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = Not InputIsCommand
End Sub

C# version:

public Form1() //Form constructor.
    textBox1.KeyPress += textBox1_KeyPress;
    textBox1.KeyDown += textBox1_KeyDown;

bool InputIsCommand = false;

private void textBox1_KeyDown(Object sender, System.Windows.Forms.KeyEventArgs e)
    if(e.Control == true && (e.KeyCode == Keys.V || e.KeyCode == Keys.C))
        InputIsCommand = true;

private void textBox1_KeyPress(Object sender, System.Windows.Forms.KeyPressEventArgs e)
    e.Handled = !InputIsCommand;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download