What's the correct way to convert this event handler registration from C# to VB.net?

吃可爱长大的小学妹 提交于 2021-02-05 06:57:05

问题


I'm trying to port some code over from C# to VB.net and I am having trouble with a simple event handler.

C#:

hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);

I've written it as such in VB.net:

AddHandler hook.KeyPressed, AddressOf hook_KeyPressed

But my conversion is missing any reference to KeyPressedEventArgs in the C# code and i'm not sure if I'm doing this right. Any help would be appreciated.


回答1:


Remember, that an event is a delegate. To subscribe to the event, the signature of the event handler must be the same as the delegate. As long as your method has the proper signature, you have done it right. Just ensure your event handler's EventArgs parameter is of the KeyPressedEventArgs type.

C#:

hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);

New C# Syntax:

hook.KeyPressed += hook_KeyPressed;

VB.net

AddHandler hook.KeyPressed, AddressOf hook_KeyPressed

Handler in VB.net:

Sub hook_KeyPressed(ByVal sender As Object, ByVal e As KeyPressedEventArgs)
    'code here
End Sub


来源:https://stackoverflow.com/questions/28387577/whats-the-correct-way-to-convert-this-event-handler-registration-from-c-sharp-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!