user310291
user310291

Reputation: 38180

How to reference the current control (the one which has focus generically) in C# winform?

I'm used to reference the current control in access vba, how to do so in C# winform ?

Upvotes: 1

Views: 2819

Answers (2)

Jeff Ogata
Jeff Ogata

Reputation: 57783

You can also use the form's ActiveControl property.

I took codekaizen's code and dropped it into a form along with a timer and several controls (a DataGridView, Panel, and a Button and CheckBox in the Panel). Added this code in the timer's Tick event:

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = ActiveControl.Name;
    label2.Text = GetFocusedControl().Name;
}

and they reported the same active control as I clicked from one control to another.

Upvotes: 2

codekaizen
codekaizen

Reputation: 27419

I'm not sure if there is a better method, but P\Invoke solves this for me:

private static Control GetFocusedControl()
{
    Control focused = null;
    var handle = GetFocusedControlHandle();

    if (handle != IntPtr.Zero)
    {
        focused = Control.FromHandle(handle);
    }

    return focused;
}

// ...
[DllImport("user32.dll")]
private static extern IntPtr GetFocusedControlHandle();

Upvotes: 0

Related Questions