定时器消息:
在程序中创建定时器,当到达时间间隔时,定时器会向程序发送一个WM_TIMER消息。定时器的精度是毫秒,但是准确度很低。
附带信息:
wParam: 定时器ID
lParam: 定时器处理函数的指针。
创建和销毁定时器:
UINT_PTR SetTimer(
HWND hWnd, //定时器窗口句柄
UINT_PTR nIDEvent, //定时器ID
UINT uElapse, //时间间隔
TIMERPROC lpTimerFunc //定时器处理函数指针(一般NULL)
);成功返回0
BOOL KillTimer(
HWND hWnd, // 定时器窗口句柄
UINT_PTR uIDEvent //定时器ID
};
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
HANDLE g_hOutput;
void OnTimer(HWND hWnd, WPARAM wParam) {
char szText[256] = { 0 };
sprintf(szText, "WM_TIMER:定时器ID=%d\n", wParam);
WriteConsole(g_hOutput, szText, strlen(szText), NULL, NULL);
}
//窗口处理函数(自定义,处理消息)
LRESULT CALLBACK WndProc(HWND hWnd, UINT msgId, WPARAM wParam, LPARAM lParam) {
switch (msgId) {
case WM_TIMER:
OnTimer(hWnd, wParam);
break;
case WM_CREATE:
SetTimer(hWnd, 1, 1000, NULL);
SetTimer(hWnd, 2, 2000, NULL);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, msgId, wParam, lParam);
}
//入口函数
int CALLBACK WinMain(HINSTANCE hIns, HINSTANCE hPreIns, LPSTR lpCmdLine, int nCmdShow) {
AllocConsole();
g_hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
//注册窗口类
WNDCLASS wc = { 0 };
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.hCursor = NULL;
wc.hIcon = NULL;
wc.hInstance = hIns;
wc.lpfnWndProc = WndProc;
TCHAR name[] = TEXT("Main");
wc.lpszClassName = name;
wc.lpszMenuName = NULL;
wc.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wc);//将以上所有赋值全部写入操作系统。
//在内存中创建窗口
HWND hWnd = CreateWindow(name, TEXT("title"), WS_OVERLAPPEDWINDOW, 100, 100, 500, 500, NULL, NULL, hIns, NULL);
//显示窗口
ShowWindow(hWnd, SW_SHOW);
UpdateWindow(hWnd);
//消息循环
MSG nMsg = { 0 };
while (GetMessage(&nMsg, NULL, 0, 0)) {
TranslateMessage(&nMsg);
DispatchMessage(&nMsg);//将消息交给窗口处理函数来处理
}
return 0;
}