tags:

views:

38

answers:

2

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

A: 

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();
codekaizen
Wow I hope that's there's something better yes ... or did MS forget an obvious feature but +1 for your clever code :)
You're doing things the hard way.
Bevan
+2  A: 

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.

adrift
I'm so happy thank you :)