简体   繁体   中英

How to call C# event from VB.Net

I have a C# class library. In that class I have declared an event as a property

private static event MouseEventHandler s_MouseClick;
public static event MouseEventHandler MouseClick
{
    add
    {
        s_MouseClick += value;
    }
    remove
    {
        s_MouseClick -= value;
    }
} 

I have another project written in VB.net, On click of a button I want to do something like this:

cls.MouseClick += cls_MouseClick;

void cls_MouseClick(object sender, KeyPressEventArgs e)
{
}

This is how I would do it in C#. But how do I do it in VB?

In VB, to register an event handler use AddHandler :

AddHandler cls.MouseClick, AddressOf cls_MouseClick

Use RemoveHandler to unregister the event handler.

Alternatively, you can use a declarative syntax. That is: declare the member as follows:

Private WithEvents cls As YourClassType

And declare the handler like this:

Private Sub cls_MouseClick(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles cls.MouseClick
End Sub

Now you do not need to register the handler manually.

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