Reputation: 243
I have implemented the custom button control with some additional options. And added my custom button into the form. When i set the Form.Acception is the added custom button, then I want to do some customization in the Button. I want to customize the button appearance in the Custom button class implementation, when it marked as AcceptButton of the Form.
Anyone suggest how can i know the button is marked as AcceptButton of the form in Button class?
Upvotes: 3
Views: 403
Reputation: 5756
WRONG:
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (((Form)this.TopLevelControl).AcceptButton == this) .... }
UPD:
public class MyButton : Button
{
public override void NotifyDefault(bool value)
{
if (this.IsDefault != value)
{
this.IsDefault = value;
}
if (IsDefault)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Color.Green;
}
}
}
Upvotes: 0
Reputation: 22083
You could traverse the parents to find the form via the parent property of its base class Control
:
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
private Form CheckParentForm(Control current)
{
// if the current is a form, return it.
if (current is Form)
return (Form)current;
// if the parent of the current not is null,
if (current.Parent != null)
// check his parent.
return CheckParentForm(current.Parent);
// there is no parent found and we didn't find a Form.
return null;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
// find the parent form.
var form = CheckParentForm(this);
// if a form was found,
if (form != null)
// check if this is set as accept button
if (this == form.AcceptButton)
// for example, change the background color (i used for testing)
this.BackColor = Color.RosyBrown;
}
}
Because of the recursion, it also works when the Button is placed on a Panel.
Note: The accept button must be set before OnCreateControl is called (for example in the form's constructor)
After some googling I found a standard implementation:
You can also use: this.FindForm();
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
var form = FindForm();
if (form != null)
if (this == form.AcceptButton)
this.BackColor = Color.RosyBrown;
}
}
Event shorter in C# 6.0:
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
if (this == FindForm()?.AcceptButton)
this.BackColor = Color.RosyBrown;
}
}
\o/
Upvotes: -1