Prevent existing text from being selected when entering a control

I’m trying to prevent the existing code from being selected when a particular control gets focus. I’d like no selection to exist, and the cursor to be placed at the end of the text.

The following doesn’t seem to work

private void txtTest1_GotFocus(object sender, System.EventArgs args)
	{
		// ** Place Event Handling Code Here **
		txtTest1.SelectionStart = txtTest1.Text.Length;
		txtTest1.SelectionLength = 0;
	}

Is the built-in selecting process something that happens after the GotFocus() event fires?

Try AfterEnterEditMode,

private void txtTest1_AfterEnterEditMode(object sender, System.EventArgs args)
	{
		// ** Place Event Handling Code Here **
		txtTest1.SelectionStart = txtTest1.Text.Length;
		txtTest1.SelectionLength = 0;
	}
1 Like

Now something is really weird…

I set txtTest1.GotFocus() to just have the following line:
txtTest1.Text = "Set via GotFocus()";

The idea was to see if that controls text was being selected before or after the GotFocus() executed. But now my GotFocus is acting more like LostFocus. If I tab to the control, the existing text doesn’t change. but when I tab out of that control, the text changes to my static value. Even if I had manually changed the text before tabbing out.

I see the same thing, weird, I know the focus events can be inconsistent.

At the Winforms level GotFocus and LostFocus are low level events that msdn recommendeds to not use. They recommend using Enter and Leave, which perform predictably in Epicor.

1 Like