Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Invoke method in a file of extensions/methods?

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.

like image 724
The Mask Avatar asked Dec 16 '11 16:12

The Mask


People also ask

How do you call an extension method?

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.

What is invoke () in C#?

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.

Can extension methods access private methods?

Extension methods cannot access private variables in the type they are extending.

Can you add extension methods to an existing static class?

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.


2 Answers

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.

like image 134
Jason Down Avatar answered Sep 28 '22 08:09

Jason Down


Change

Invoke((UpdateState)delegate …

to

label.Invoke((UpdateState)delegate …
like image 29
Ondrej Tucny Avatar answered Sep 28 '22 09:09

Ondrej Tucny