C语言实现定时器的详细教程

#include <stdio.h>
#include <windows.h>
void CALLBACK timer_handler(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
    printf("Timer expired!\n");
}

int main() {
    // 创建窗口,用于接收消息
    HWND hwnd = CreateWindow("STATIC", "", 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL);

    // 创建定时器,每隔2秒触发一次
    UINT_PTR timerId = SetTimer(hwnd, 1, 2000, timer_handler);

    // 等待消息循环结束
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // 删除定时器
    KillTimer(hwnd, timerId);

    return 0;
}

代码解释:
#include <stdio.h>
#include <windows.h>
这两行是引入所需的标准库头文件。

void CALLBACK timer_handler(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
    printf("Timer expired!\n");
}
定义了一个回调函数 timer_handler,当定时器到期时会被调用。在此示例中,它只简单地打印一条消息表示定时器已经过期。

int main() {
    // 创建窗口,用于接收消息
    HWND hwnd = CreateWindow("STATIC", "", 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
创建一个静态窗口,用于接收消息。这里使用了 Windows API 中的 CreateWindow() 函数来创建窗口。这个窗口不具有实际的可见界面,仅用于接收消息。

UINT_PTR timerId = SetTimer(hwnd, 1, 2000, timer_handler);
创建一个定时器,并将其添加到窗口消息队列中。这里使用了 Windows API 中的 SetTimer() 函数来设置定时器。第一个参数 hwnd 指定了要接收定时器消息的窗口句柄,第二个参数是定时器 ID,第三个参数是定时器的时间间隔(单位:毫秒),第四个参数是定时器到期时的回调函数。

MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
进入消息循环,等待窗口接收到消息。这里使用了 Windows API 中的 GetMessage() 函数来从消息队列中获取消息,并使用 TranslateMessage() 和 DispatchMessage() 函数将消息翻译并分发给窗口过程进行处理。

KillTimer(hwnd, timerId);
删除定时器。这里使用了 Windows API 中的 KillTimer() 函数来删除先前创建的定时器。

return 0;
程序正常结束,返回 0 表示成功运行。
该示例使用了 Windows API 中的函数来创建和管理定时器,并且利用窗口消息循环接收定时器消息。

物联沃分享整理
物联沃-IOTWORD物联网 » C语言实现定时器的详细教程

发表评论