MaskedTextBox.SelectAll on GotFocus not working with mouse

I want to select all the contents of MaskedTextBox when clicks (or tabs) on the control, so they can easily replace the old content. I tried calling SelectAll() on the Enter event, but that didn't work.

I switched to using the GotFocus event, which works great when typing in controls, but doesn't work when I click on it with the mouse. I would only like to select all the contents the first time I enter / focus on the control (subsequent clicks can be used to position the cursor to edit existing text).

I added a button and tried to call SelectAll() on the button click event, but did nothing. What's happening? This is mistake?

How can I get around this?


Playback Steps

  • Create a new Windows Form application in .NET 4.0 in Visual Studio 2010.
  • Add TextBox , MaskedTextBox and Button to the default form
  • Change the Mask property of MaskedTextBox to "_____".
  • Add some event handlers:

     private void maskedTextBox1_GotFocus(object sender, EventArgs e) { Debug.WriteLine("GotFocus"); maskedTextBox1.SelectAll(); } private void button1_Click(object sender, EventArgs e) { Debug.WriteLine("Click"); maskedTextBox1.SelectAll(); } 
  • Run the program, enter some data in the MaskedTextBox tab to go to the controls. It selects the contents of MaskedTextBox.

  • Select a different text block. Try clicking MaskedTextBox. The output shows that the GotFocus event was triggered, but no text was selected.
  • Try clicking the button on the form. Text is not selectable.

Tested in Visual Studio 2010 with .NET 4.0 in a Windows Forms Application Project


Why is this not a duplicate of TextBox.SelectAll () does not work with TAB

If you notice, the title says "SelectAll does not work with TAB". In my case, it works with Tab , it does not work with the mouse - the exact opposite scenario. The answer to this question is to use the GotFocus event. I already use the GotFocus event, but it does not work. This answer does not answer this question. This is clearly not a duplicate. If I'm wrong, explain in the comments.

+6
source share
1 answer

Your SelectAll() will be overwritten with the default functionality for the masked text field. I would use the Enter event, it allows you to enter a tab or mouse click into a masked text field. Most likely, you will need to use the BeginInvoke method. Try the code below. This worked for me when I tried ...

 private void maskedTextBox1_Enter(object sender, EventArgs e) { BeginInvoke((Action) delegate { SetMaskedTextBoxSelectAll((MaskedTextBox) sender); }); } private void SetMaskedTextBoxSelectAll(MaskedTextBox txtbox) { txtbox.SelectAll(); } 
+8
source

Source: https://habr.com/ru/post/982712/


All Articles