Reputation: 3338
for detect that which controls is activated in windows form
this.ActiveControl = NameOfControl;
how about detect type of control , for example active control is button or textbox ?
New Edit:
i want to do something on keypress if active control is type of textBox else do nothing
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (this.ActiveControl == xxxx)
{
//do SomeThing
}
return base.ProcessCmdKey(ref msg, keyData);
}
in xxx i should type of name of control , but how can i do for all control that is type of text box?
Upvotes: 2
Views: 5175
Reputation: 8079
You could iterate over all controls on your Form and set an event handler for the GotFocus Event. In this Event handler you would set the variable:
Control ActiveControl = null;
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if(c is TextBox)
{
c.GotFocus += (s, o) =>
{
this.ActiveControl = s as Control;
};
}
}
}
When you use your ActiveControl objekt test for the type with the "is" operator.
Upvotes: 1
Reputation: 847
Use .GetType()
, for example this.ActiveControl.GetType() == typeof(Button)
Upvotes: 1
Reputation: 7804
To determine whether an active control is a Button or TextBox you could use the is
operator. The is operator checks if an object is compatible with a given type. If the Control
is compatible with a Button
and the expression yields true, then the Control is a Button.
if (ActiveControl is Button)
{
}
else if (ActiveControl is TextBox)
{
}
Upvotes: 3