Reputation: 38180
I'm used to reference the current control in access vba, how to do so in C# winform ?
Upvotes: 1
Views: 2819
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
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