I have the following working code sample:
public void ClearLogText() => this.TxtLog.Invoke((Action)delegate {this.TxtLog.Text = string.Empty;});
How would I properly add parameters?
public void SetControlText(Control control, string text) => this.Invoke((Action<Control, string>delegate (Control x, string y) {x.Text = y;});
The problem that I have is how to use the parameters into the function, in this case control
and text
.
Note: The method could have been anything. It is the concept that I care about, not what the method does. That was simply the first thing that came to mind.
Visual Studio complains about the obvious, namely that I am not using the arguments into the method.
I already know how to work with Actions
, such as illustrated by this answer. What throws me off is the Invoke
and delegate
parts.
private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
Action<string, BalloonTip.BalloonType> act =
(m, b) => BalloonTip.ShowBalloon(m, b);
act(message, ballType);
}
I would also like to keep the answer to one line using the construct this.X.Invoke((Action)delegate...
, hence this question, otherwise the answer would be:
public delegate void DelegateSetControlText(Control control, string text);
public void SetControlText(Control control, string text)
{
if (true == this.InvokeRequired)
{
Program.DelegateSetControlText d = new Program.DelegateSetControlText(this.SetControlText);
this.Invoke(d, new object[] { control, text });
}
else
control.Text = text;
}
There's no need to include the delegate
cast in the actual call.
The parameters go into the 2nd argument of the Invoke
method, being a params
object array, here containing control
and text
.
public void SetControlText(Control control, string text)
=> this.Invoke((Action<Control, string>)((ctrl, txt) => ctrl.Text = txt), control, text);