ProblemYou need to have some action occur on a regular basis in your form. SolutionSample code folder: Chapter 04\ClockTimer Use a Timer control, and set it for the desired interval. Create a new Windows Forms application, and add a Label control named CurrentTime to the form. Also add a Timer control to the form, and name it ClockTimer. Set its Interval property to 1000, and set its Enabled property to true. Then add the following source code to the form's code template: Private Sub ClockTimer_Tick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ClockTimer.Tick CurrentTime.Text = Now.ToLongTimeString End Sub When you run the program, that label updates once each second with the current time. DiscussionThe Timer control's Interval property sets the time between Tick events in milliseconds (1,000 per second). Although you can set the Interval as low as one millisecond, the timer's resolution is limited by your system's hardware and operating-system-level factors. The Tick event fires at approximately the interval you specify, if nothing more important is going on. If the code within your Tick event handler is still running when the next Tick event should occur, that subsequent Tick event is disposed without a call to the event handler. See AlsoRecipe 14.8 shows how to have a section of code sleep, or take a small break. Some older Visual Basic code used timers for this purpose, although a timer is not the best solution in this case. |