KillTimer无法删除指定定时器问题求助
KillTimer无法删除指定定时器问题求助
我最近写了一段代码来学习SetTimer和KillTimer的用法,逻辑是这样的:在WM_CREATE消息里设置一个定时器,然后在定时器的回调函数里调用KillTimer,想让定时器只被触发一次。我还在回调函数里加了一个MessageBox,用来提示定时器被调用了,本来以为这个弹窗只会出现一次——毕竟弹完之后就会调用KillTimer关掉定时器了。
但程序的运行结果完全不符合预期,KillTimer好像根本没按要求停止定时器,反而程序一直在弹出MessageBox,停都停不下来。有没有大佬能帮我看看问题出在哪?
下面是我的代码:
#include <stdio.h> #include <windows.h> VOID CALLBACK timer_proc(HWND hwnd, UINT msg, UINT timer_id, DWORD time) { char buf[1024]; sprintf(buf, "TIMER PROC CALLED AT %d, ID %d", time, timer_id); MessageBoxA(hwnd, buf, "MSGBOX", MB_ICONINFORMATION); KillTimer(hwnd, timer_id); } void wm_paint(HWND hwnd) { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); TextOutA(hdc, 20, 20, "Hi?", 3); EndPaint(hwnd, &ps); } LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { switch (msg) { case WM_CREATE: SetTimer(hwnd, 1, 500, timer_proc); return 0; case WM_PAINT: wm_paint(hwnd); return 0; case WM_SIZE: return 0; case WM_DESTROY: PostQuitMessage(0); return 0; default: return DefWindowProc(hwnd, msg, wp, lp); } } void init_wndclass(WNDCLASS *w, HINSTANCE hinstance, char *class_name) { w->style = CS_HREDRAW | CS_VREDRAW; w->lpfnWndProc = wndproc; w->cbClsExtra = w->cbWndExtra = 0; w->hInstance = hinstance; w->hIcon = LoadIcon(NULL, IDI_APPLICATION); w->hCursor = LoadCursor(NULL, IDC_ARROW); w->hbrBackground = GetStockObject(WHITE_BRUSH); w->lpszMenuName = NULL; w->lpszClassName = class_name; } HWND create_window(HINSTANCE hinstance) { WNDCLASS wndclass; char *class_name = "main window class"; init_wndclass(&wndclass, hinstance, class_name); RegisterClass(&wndclass); return CreateWindowA(class_name, "TIMER TEST", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, // position CW_USEDEFAULT, CW_USEDEFAULT, // window size NULL, /* owner window */ NULL, /* menu */ hinstance, NULL /* window-creation data */); } int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev, PSTR cmdline, int cmdshow) { HWND hwnd = create_window(hinstance); ShowWindow(hwnd, cmdshow); UpdateWindow(hwnd); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
备注:内容来源于stack exchange,提问作者Limina102
相关产品推荐
相关产品推荐

