TextBox.SelectAll() doesn't work - sometimes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thesarg
    New Member
    • Oct 2018
    • 2

    TextBox.SelectAll() doesn't work - sometimes

    Using VS2008, Windows Forms Application

    In a TextBox::KeyDow n event I check to see if the Enter Key has been pressed, and if so, I perform some action then attempt to select all of the text using SelectAll(), as follows:
    Code:
    private void SelectAllTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (Keys.Enter == e.KeyCode)
        {
    	PerformSomeAction();
            SelectAllTextBox.SelectAll();
        }
    }
    It works as expected if I manually enter text into the TextBox then press enter, but if I use a barcode reader to enter the text (with a <CR>), the PerformSomeActi on() method executes but the SelectAll() method appears to not select the text. I'm guessing the difference is the timing between characters.
    To get passed the issue I changed to code to use a Timer as follows:
    Code:
    private void SelectAllTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (Keys.Enter == e.KeyCode)
        {
    	PerformSomeAction();
            HackTimer.Start();
        }
    }
    private void HackTimer_Tick(object sender, EventArgs e)
    {
        HackTimer.Stop();
        SelectAllTextBox.SelectAll();
    }
    This works if the Timer Interval is set to a value greater than 10ms.
    Note: the PerformSomeActi on() method is irrelevant.

    Can someone explain the timing involved and why, without the Timer, it doesn't work?
  • Luk3r
    Contributor
    • Jan 2014
    • 300

    #2
    I believe this is a case of needing to suppress the event because you're not actually wanting the ENTER key to do work, simply trigger work. Add the following code after your ".SelectAll ()" code.

    Code:
    e.SuppressKeyPess  = true;

    Comment

    • thesarg
      New Member
      • Oct 2018
      • 2

      #3
      Thanks for the reply Luk3r. Unfortunately adding e.SuppressKeyPr ess = true; doesn't make a difference. I actually have that in the code already to suppress the beep that occurs on a non-multiline TextBox. What's odd about my problem is that if I use the keyboard to enter text into the TextBox, then press the Enter key, then it works - all of the text gets selected. But if I use a barcode reader to enter text into the TextBox (with an automatic Cr), then it doesn't work - none of the text get selected. This seems to be a timing issue since the barcode reader is entering text far quicker than I can possibly type. Thanks again.

      Comment

      Working...