2

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.

cowsay
  • 1,282
  • 1
  • 15
  • 36
  • Telerik has a good C# to VD.NET conversion utility, which I have found useful and hope you do too. http://converter.telerik.com/ – ron tornambe Feb 07 '15 at 21:31
  • Rewrite the C# code first: `hook.KeyPressed += hook_KeyPressed;` Now it is obvious. – Hans Passant Feb 07 '15 at 21:36
  • @rontornambe All of the code converters out there that I've found fail to properly convert event handlers, including Telerik. Try it yourself with the C# code snippet in my post. It doesn't bother using VB.net's AddHandler. – cowsay Feb 07 '15 at 21:36

1 Answers1

4

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
saegeoff
  • 551
  • 5
  • 12
  • That is exactly what I have, it just didn't seem right because the C# code registers the event handler with mention of KeyPressedEventArgs, whereas the VB.net code does not. I guess that comes into play in the hook_KeyPressed arguments? – cowsay Feb 07 '15 at 21:40
  • 1
    Yes, technically in C# you don't need the event args either. In your example, using the new delegate is the old way. Now it is done with new syntax: hook.KeyPressed += hook_KeyPressed; – saegeoff Feb 07 '15 at 21:41