Select All (ctrl+A) For A Textbox

Have you ever tried to push ctrl+A on a multi-line or single line textbox in a Dot Net Windows Forms application to select all of the text? If you have you would know that it doesn’t work. That’s right, standard windows functionality doesn’t work for the TextBox control. So here’s how to fix it using a custom control.

namespace MyTextBoxDemo
{ public class MyTextBox : System.Windows.Forms.TextBox { protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { if (e.Control && (e.KeyCode == System.Windows.Forms.Keys.A)) { this.SelectAll(); e.SuppressKeyPress = true; e.Handled = true; } else base.OnKeyDown(e); } } }

Above you see the complete code. It is very simple and works by overriding the OnKeyDown event that the base TextBox class has. We check to see if the ctrl key is pressed in conjunction with the A key. If this is true we run the SelectAll() method which does all the work. Then we’re just left with suppressing the OnKeyPress event so we don’t get that annoying "beep!" and setting the handled function to true. If ctrl+A was not pressed then we proceed with the base OnKeyDown event, ensuring the MyTextBox control works exactly as the standard TextBox control does.

The MyTextBox control should be available to your project immediately after a build. It will also add the control to the toolbox automatically.

Hopefully this has added the standard functionality back into our dot net application and given you some hints on customising the TextBox control even further.


This entry was posted in .NET and tagged , , , . Bookmark the permalink.

9 Responses to Select All (ctrl+A) For A Textbox

  1. Pingback: Select All (ctrl+A) For Textbox - Adam Schroder

  2. Manu says:

    Just what I’ve been looking for ! Thanks πŸ™‚

  3. Nate says:

    Thanks, that did the trick

  4. Nir says:

    Great solution, works great


  5. Locksmith says:

    I’ve been trying to do this for a while, thanks for the insight!

  6. Joshua says:

    Awesome, thanks for this πŸ™‚

  7. thaiberious says:

    Why do you have to create a whole new control for this? This is all you need:

    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.Control And e.KeyCode = System.Windows.Forms.Keys.A Then
    e.SuppressKeyPress = True
    e.Handled = True
    End If
    End Sub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s