Well, I'm writing a file of extensions/method useful to strings,label,linklabels,class etc.
but, I have a problem. I have an showMessage()
method that change the Text of label, works fine. But I decide to do that works with thread execution, then I do this:
namespace LabelExtensions
{
public static class LabelExtensionsClass
{
private delegate void UpdateState();
public static void ShowMessage(this Label label, string text)
{
if (label.InvokeRequired)
{
label.Invoke((UpdateState)delegate
{
label.Text = text;
});
}
else
{
label.Text = text;
}
}
}
}
sorry, it was a typo. I typed this code on forum. the error continue.
according the documentation,to use the Invoke method need to imports:
Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
then I did:
using System.Windows.Forms;
but this returns same error:
The name 'Invoke' does not exist in the current context
how I fix this?
Thanks in advance.
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception.
Extension methods cannot access private variables in the type they are extending.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
Why not just do this:
label.BeginInvoke( (Action) (() => label.Text = text));
There is no need to create your own delegate. Just use the built-in Action delegate. You should probably create your extension method for the base Control class instead of the Label class. It'll be more reusable.
Change
Invoke((UpdateState)delegate …
to
label.Invoke((UpdateState)delegate …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With