itchibahn
itchibahn

Reputation: 75

How to highlight the control when it gets focus?

I can highlight the text in an individual MaskedTextBox when it gets focus using:

this.myTextBox.SelectAll();

But, I want to do it for all MaskedTextBox when a mouse click event occurs. Instead of adding 30 individual event method for each MaskedTextbox, I want to select all MaskedTextBox and have one event method to take care of it, ie:

private void MouseClickedForMaskedTextBox(object sender, MouseEventArgs e)
{
    this.ActiveControl.SelectAll();
}

But SelectAll is not available for this.ActiveControl. Is there a way to get around it?

Upvotes: 4

Views: 2158

Answers (4)

Kong Fan
Kong Fan

Reputation: 3

I found another way by creating or edit your User Control that inherits MaskedTextBox. In the designer you set true the property "OnEnterSelectAll".

public partial class MaskedTextBoxX : MaskedTextBox
{
    public MaskedTextBoxX()
    {
        InitializeComponent();
        Inicializar();
        }

    // ===============================
    // Campos Añadidos
    // ===============================

    public bool OnEnterSelectAll { get; set; } = false;


    // ===============================
    // Metodos
    // ===============================

    private void Inicializar()
    {
        // *** SELECCIONAR TODO el MarkedTextBox
        Click += delegate { if (OnEnterSelectAll) SelectAll(); };
    }
}

Upvotes: 0

fsbflavio
fsbflavio

Reputation: 874

Simply do that:

private void maskedTextBox1_Enter(object sender, EventArgs e)
{
   this.BeginInvoke((MethodInvoker) delegate() {
   maskedTextBox1.SelectAll();
   });
}

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190897

sender will be the target of the event.

You could cast sender:

MaskedTextBox maskedTextBox = sender as MaskedTextBox;
if (maskedTextBox != null) { maskedTextBox.SelectAll(); }

Or in C# 7,

if (sender is MaskedTextBox maskedTextBox) 
{
    maskedTextBox.SelectAll();
} 

Another improvement is to use TextBoxBase and it will work with TextBox and RichTextBox as well.

Upvotes: 4

Mazen Alsenih
Mazen Alsenih

Reputation: 101

Put the following code in the form's constructor:

        foreach (Control c in Controls)
        {
            if (c is TextBox)
            {
                TextBox tb = c as TextBox;
                tb.GotFocus += delegate { tb.SelectAll(); };
            }
        }

Upvotes: 1

Related Questions