Search code examples
c#vb.nettimer

How is this VB timer working with no declaration?


I'm working on translating a VB.NET application to C#.NET (and I've never worked with either before, although I do know C++). I've got most of it working, but there's one thing stumping me. There's a function in the VB that is

Private Sub timerReadCommands_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerReadCommands.Tick

But timerReadCommands is not declared anywhere. There's no button called that, there's no variable called that, Visual Studio says this method has zero references, I even tried checking the other file to see if it was somehow declared over there. This VB application (and method) works as expected, but it's not working in the C# version. I figure it must be declared somewhere, and I just can't find the declaration. In the C# application, I tried

Timer timerReadCommands = new Timer();

to declare it, which eliminated the undeclared variable errors, but the method never runs.

I've tried Googling to figure out how the VB is working, in order to try to mimic it in C#, but I'm only getting results from people whose timers aren't working. I need to know why mine is. Alternatively, I need to know how to make my C# one work.

Thanks!


Solution

  • The C# code to create the timer is missing this excerpt from the VB:

    Handles timerReadCommands.Tick
    

    C# doesn't support this feature, so you need to add the handler with a 2nd line of C# code, usually somewhere near the call to InitializeComponent():

    timerReadCommands.Click += new EventHandler(timerReadCommands_Tick);
    

    Additionally, that timer must be declared in the VB project somewhere, or that Handles clause would not compile. If you can load the VB project in Visual Studio, you should be able to right-click the timerReadCommands text in the Handles clause and choose Go to definition from the context menu; that will show you exactly where the timer is declared... probably a formname.designer.vb file.

    The designer files are there for Visual Studio to use and manage. They exist to separate the code created by the forms designer from your own code, so the forms designer does not over-write or change something you wanted to keep. You should not change anything in the designer files. Instead, you can create this timer by dragging to the form from the toolbox and giving it the same name.