I'm getting tired of trying to figure out when and where an invoke is required. Rewriting this code over and over inline is tedious. I have created the method below to help solve this issue:
public void RunInvoked(object sender, Action method)
{
Control This = sender as Control;
if (This.InvokeRequired)
{
if (!This.IsHandleCreated) return;
This.Invoke((MethodInvoker)delegate ()
{
method();
});
}
else
{
method();
}
}
(example method) And I call it as such :
private void EnableButton(bool enable)
{
RunInvoked(this, () =>
{
if (enable)
{
this.buttonSet.Enabled = true;
this.buttonSet.ForeColor = Color.Black;
this.buttonSet.BackColor = Color.LightBlue;
}
else
{
this.buttonSet.Enabled = false;
this.buttonSet.ForeColor = Color.Gray;
this.buttonSet.BackColor = SystemColors.ButtonFace;
}
this.buttonSet.Update();
});
}
I just want to make sure that this is sound logic and that it is not overlooking some glaring issues that I am unaware of before I start to implement this throughout my code. Also any help on making it even more generic would be appreciated if you feel so inclined. Thank you!