Implementing System Timers
Introduction
Welcome to System Events and Integration. We are at the very beginning of this course, which is a great place to start with something practical. In this first lesson, we will build a window that updates itself once per second by using a system timer. The key idea is simple: we want periodic work to happen without freezing the application.
By the end of this lesson, we will understand how to start a timer with SetTimer, receive WM_TIMER messages, update a label dynamically, and stop the timer cleanly when the window closes. This pattern is very common in event-driven desktop programs.
Why System Timers Matter
In WinAPI, the window does not run code in a constant loop that checks the clock again and again. Instead, Windows sends messages to our program, and our program reacts to them. A system timer fits nicely into that model: we ask Windows to notify our window every so often, then we handle that notification like any other message.
This matters because we want the interface to stay responsive. If we used Sleep inside the main thread, the window would pause and stop reacting to input. A timer avoids that problem; Windows delivers WM_TIMER through the normal message system. For a simple counter, an interval of milliseconds, which is second, is exactly what we need.
Preparing The Program Structure
Before we start the timer itself, we need a few building blocks: Unicode support for wide strings, numeric IDs for the timer and label, and a window procedure to receive messages. We also keep a counter that survives across message calls because the timer will arrive many times during the life of the window.
This structure should look familiar. We begin by defining unique IDs for both the timer and the label to keep our controls organized. Within the window procedure, we declare secondsElapsed as a static variable; this ensures the counter persists across multiple function calls as the timer fires. Finally, DefWindowProcW handles any messages we don't explicitly process, ensuring our window maintains its standard behavior.
