开发者

Issue running C# function from another C# application

开发者 https://www.devze.com 2023-02-21 02:30 出处:网络
I have a C# Windows Form that contains a function called automation.I then have a C# console application that I am trying to use to call the function of the Windows Form.I have created the reference a

I have a C# Windows Form that contains a function called automation. I then have a C# console application that I am trying to use to call the function of the Windows Form. I have created the reference and have gotten this far:

Form1 FormInstance = new Form1();
FormInstance.automation += new EventHandler(?);

My question is, I have tried to add something where my question mark is but I continue getting an error. If I set it up like this:

FormInstance.automation += new EventHandler(NewHandler);

I get "NewHandler" doe开发者_运维问答s not exist in the current context.

And if I create

public void NewHandler(object sender, EventArgs e)

I get An object reference is required for the non-static field, method, or property.

I can not figure out what I am doing wrong.


It is supposed to be object.NewHandler, where object may be this if this occurs within the context of a member method. You can be forgiven for tripping this up because most member references can be implicit but this one has to be explicit.


At a high level it works something like this:

public static void Main(string[] args)
{
    Form x = new Form();
    x.Method = new EventHandler(MyHandler);
}

public static void MyHandler(object sender, EventArgs e)
{
   // Stuff
}

It looks like you haven't marked your method with the static keyword (if invoking this via a static method like a console main). You also need to make sure you're assigning the appropriate delegate to the event; i.e. automation in your method needs to be able to accept an EventHandler delegate.


The simplest way is to make your event handler method static

public static void NewHandler(object sender, EventArgs e) 
0

精彩评论

暂无评论...
验证码 换一张
取 消