Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribing events in VB.NET

Tags:

vb.net

events

wpf

I'm trying to convert some C# code to VB.NET.

I have the following in C# (which works)

m_switchImageTimer = new DispatcherTimer();
m_switchImageTimer.Interval = Interval;
m_switchImageTimer.Tick += (s, e) => LoadNextImage();

The key line I'm struggling to convert successfully is:

m_switchImageTimer.Tick += (s, e) => LoadNextImage();

What I have tried is:

m_switchImageTimer.Tick += Function(s, e) LoadNextImage()
m_switchImageTimer.Tick += New EventHandler(AddressOf LoadNextImage)

Neither of these are working.

The first attempt produces two errors, the first VS2010 highlights under m_switchImageTimer.Tick:

Error 1 'Public Event Tick(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event

and highlighted under LoadNextImage() produces the following error:

Error 3 Expression does not produce a value.

The second attempt produces the same error:

Error 1 'Public Event Tick(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.

How can I convert the C# code to VB.NET?

Thanks Ben

like image 459
Ben Avatar asked Aug 28 '11 10:08

Ben


People also ask

What is an event procedure in VB net?

Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an occurrence in a program. Function Procedures return a value to the calling code. They can perform other actions before returning.


1 Answers

Subscribing to events in VB.NET requires either the AddHandler or Handles keyword. You will also have a problem with the lambda, the Function keyword requires an expression that returns a value. In VS2010 you can write this:

    AddHandler m_switchImageTimer.Tick, Sub(s, e) LoadNextImage()

In earlier versions, you need to either change the LoadNextImage() method declaration or use a little private helper method with the correct signature:

    AddHandler m_switchImageTimer.Tick, AddressOf SwitchImageTimer_Tick
...
Private Sub SwitchImageTimer_Tick(sender As Object, e As EventArgs)
    LoadNextImage()
End Sub
like image 132
Hans Passant Avatar answered Oct 12 '22 09:10

Hans Passant