Main Contents

Select All (ctrl+A) For A Textbox

Schotime @ March 12, 2008

.NET

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.

Schotime


book mark Select All (ctrl+A) For A Textbox in del.icio.us submit Select All (ctrl+A) For A Textbox to digg.com


5 Comments

  1. Select All (ctrl+A) For Textbox - Adam Schroder March 12, 2008 @ 3:33 pm

    [...] Click here to read more.. Posted: Mar 12 2008, 03:34 PM by schotime | with no comments [...]

  2. Manu March 15, 2008 @ 3:41 am

    Just what I’ve been looking for ! Thanks :)

  3. Nate May 21, 2008 @ 11:18 am

    Thanks, that did the trick

  4. Nir June 7, 2008 @ 11:46 pm

    Great solution, works great

    Nir

  5. Locksmith September 28, 2009 @ 7:57 pm

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

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Feed
4,818 spam comments
blocked by
Akismet