方法一:创建一个线程, 反复读系统时间不就可以了? 如果定时要求不严,用Sleep就可以了。DWORD WINAPI TimerThread(LPVOID pamaram) { UINT oldTickCount, newTickCount; oldTickCount = GetTickCount(); //获取的是毫秒数 while(TRUE) { while(TRUE) { newTickCount = GetTickCount(); // 获取的是毫秒数 if(newTickCount - oldTickCount >= 60000) { oldTickCount = newTickCount; break; } else SwitchToThread(); } // 60毫秒自动调用函数 SomeFun(); } return 0; }
方法二: DLL中的线程函数可以象这样使用Timer UINT ThreadProc(LPVOID) { SetTimer(NULL, 1, 5000, NULL); MSG msg; // PeekMessage 强制系统为该线程建立消息栈 PeekMessage(&msg, NULL, NULL, NULL, FALSE); while (GetMessage(&msg, NULL, NULL, NULL)) { switch (msg.message) { case WM_TIMER: { // 这里每5秒钟执行一次 } break; } //TranslateMessage(&msg); //DispatchMessage(&msg); } KillTimer(NULL, 1); return 0; }
DWORD tidTimer; UINT uElapse; unsigned __stdcall TimerThreadProc(void *param) { MSG msg; UINT_PTR hTimer; if ((hTimer = SetTimer(NULL, NULL, uElapse, 0)) == 0) MessageBox(NULL, L"Set Timer failed.", L"Error", MB_OK); while (GetMessage(&msg, NULL, 0, 0)) { switch(msg.message) { case WM_TIMER: //... break; default: break; } } if (hTimer) KillTimer(NULL, hTimer); return 0; } _beginthreadex(NULL, 0, TimerThreadProc, NULL, 0, &tidTimer); ... PostThreadMessage(tidTimer, WM_TIMER, 0, 0); //随后的某个事件处理中启动定时器
时间: 2024-10-13 16:19:24