3

I try to convert a Visual Basic (VB) project to C# and I have no idea how to change some of codes below,

In a windows form a field and a Timer object defined like this;

Public WithEvents tim As New Timer
...
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tim.Tick
End Sub
...

How to rewrite this lines in C#?

Emrah KONDUR
  • 186
  • 1
  • 2
  • 13
  • 1
    If your rewriting this into a new c# winforms project, you presumably have a designer window, just add a new timer and double click it. – Sayse Jul 29 '15 at 07:34
  • There is no direct equivalent for WithEvents in C#. It relies on compiler magic in the VB.NET compiler that the C# compiler does not have. First convert the VB.NET code to use the AddHandler statement instead, then you'll have a very easy time converting it to C#, a machine can do it. – Hans Passant Jul 29 '15 at 08:20

1 Answers1

7

In C# you enrol an EventHandler by registering a method delegate with the event using the += operator as follows:

public Timer tim = new Timer();
tim.Tick += Timer1_Tick;

private void Timer1_Tick(object sender, EventArgs e)
{
   // Event handling code here
} 

This works because the Tick event of the Timer class implements an Event as follows:

public event EventHandler Tick

and EventHandler is a method delegate with signature:

public delegate void EventHandler(
    Object sender,
    EventArgs e
)

which is why any method that conforms to the EventHandler signature can be used as a handler.

d219
  • 2,707
  • 5
  • 31
  • 36