InvokeRequired and ToolStripStatusLabel

In my application, I have a class that is responsible for all database actions. It is called from the main class and uses delegates to call methods after the action completes. Since it is asynchronous, I have to use invoke in my GUI, so I created a simple extension method:

public static void InvokeIfRequired<T>(this T c, Action<T> action) where T: Control { if (c.InvokeRequired) { c.Invoke(new Action(() => action(c))); } else { action(c); } } 

This works fine when I try to call it in a text box:

 textBox1.InvokeIfRequired(c => { c.Text = "it works!"; }); 

but when I try to call it on ToolStripStatusLabel or ToolStripProgressBar, I get an error:

The type "System.Windows.Forms.ToolStripStatusLabel" cannot be used as you enter the parameter "T" in the generic type or method 'SimpleApp.Helpers.InvokeIfRequired (T, System.ction)'. There is no implicit link translation from 'System.Windows.Forms.ToolStripStatusLabel' to 'System.Windows.Forms.Control'.

I know this is probably a simple fix, but I just can handle it: /

+6
source share
3 answers

This is because ToolStripItem (the base for those who cause the error) is a component, not a control. Try calling the extension method on the toolbar that owns it, and configure the delegate Methods.

+9
source

I would like to add to the decision. You can get the control from the component using the GetCurrentParent method in ToolStripStatusLabel.

Instead of doing toolStripStatusLabel1.InvokeIfRequired , do toolStripStatusLabel1.GetCurrentParent().InvokeIfRequired

+1
source

Extension method using GetCurrentParent().InvokeRequired

 public static void ToolStripStatusInvokeAction<TControlType>(this TControlType control, Action<TControlType> del) where TControlType : ToolStripStatusLabel { if (control.GetCurrentParent().InvokeRequired) control.GetCurrentParent().Invoke(new Action(() => del(control))); else del(control); } 

Call extension ToolStripStatusInvokeAction:

 toolStripAppStatus.ToolStripStatusInvokeAction(t => { t.Text= "it works!"; t.ForeColor = Color.Red; }); 
0
source

Source: https://habr.com/ru/post/1434130/


All Articles