简体   繁体   中英

C# - dll event handler

I am setting a .dll file to create a new form and a new button, but i want that button to do something. Is it possible to create a event handler in a dll file?

public static byte sbuton( string er, int by,int re)
{
    Form fg = new Form();
    fg.Show();
    Button b1 = new Button();
    fg.Controls.Add(b1);
    b1.Text = er;
    b1.Location = new Point(by, re);
    return 0;
}

This is the code that creates a form with a button in it. When I try to create a new event handler, as I would in a form, I get this error: "An object reference is required for the non-static field, method or property".


  public static byte sbuton( string er, int by,int re)
    {
        Form fg = new Form();
        fg.Show();
        Button b1 = new Button();
        fg.Controls.Add(b1);
        b1.Text = er;
        b1.Location = new Point(by, re);
        b1.Click += new EventHandler(b1_click);
    }

private void b1_click(object sender , EventArgs e) { }

This is the code from the form where I want use the dll

 private void button1_Click(object sender, EventArgs e) { if (richTextBox1.Text.Contains("add") && richTextBox1.Text.Contains("buton") && richTextBox1.Text.Contains("text")) { form.sbuton("buton", 10, 10); } } 
This creates a button, but nothing happens when the button is clicked, because no event handler is assigned to it in the .dll file. And also,sorry for the bad english,it is not my native language.

What can i do? Thanks!

It's not clear from your question what the context is. Without a good, minimal , complete code example it's difficult to provide a really good answer.

But in your example, it appears that your event handler is in the same DLL (and I assume, the same class) as the sbuton() method. If that's the case, then all you need to do in order to use the event handler is make it a static method:

private static void b1_click(object sender , EventArgs e)
{
}

Now, since you didn't post any of the code in the method, never mind the full context, it's not certain that would work. Ie if there is a good reason for that method being a non-static method, then you will have to subscribe the event handler by referring to the method with a reference to an actual instance of the containing class. If that's the case, then the question commenter Daniel Kelley suggests, An object reference is required for the non-static field, method, or property? , may turn out to be appropriate for your needs after all.


Finally, note that none of this has anything to do with the code being in a DLL. You would have run into this same problem had your sbuton() method been in the same project from which you're calling it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM