转载的地址:
http://blog.163.com/linzuxin@126/blog/static/340740572008101311552948/
1.1 用WM_TIMER来设置定时器
先请看SetTimer这个API函数的原型
UINT_PTR SetTimer( HWND hWnd, // 窗口句柄 UINT_PTR nIDEvent, // 定时器ID,多个定时器时,可以通过该ID判断是哪个定时器 UINT uElapse, // 时间间隔,单位为毫秒 TIMERPROC lpTimerFunc // 回调函数 );
void CTimerTestDlg::OnTimer(UINT nIDEvent) { switch (nIDEvent) { case 24: ///处理ID为24的定时器 Draw1(); break; case 25: ///处理ID为25的定时器 Draw2(); break; } CDialog::OnTimer(nIDEvent); }
void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime) { switch(nTimerid) { case 1: ///处理ID为1的定时器 Do1(); break; case 2: ///处理ID为2的定时器 Do2(); break; } }
BOOL KillTimer( HWND hWnd, // 窗口句柄 UINT_PTR uIDEvent // ID );
#include <windows.h> #include <iostream> VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime); VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime) { std::cout < < "hello " < < std::endl; } void main() { int timer1 = 1; HWND hwndTimer; MSG msg; SetTimer(NULL,timer1,5000,TimerProc); int itemp; while ( (itemp = GetMessage(&msg, NULL,NULL,NULL))&& (itemp!=0) && (-1 != itemp)) { if (msg.message == WM_TIMER) { std::cout < < "i got the message " < < std::endl; TranslateMessage(&msg); DispatchMessage(&msg); } } }
--------------------------------------------------------------------------------------------------------------------------- // timer.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <conio.h> unsigned long WINAPI Thread(PVOID pvoid); void main() { DWORD dwThreadId; printf("use timer in workthread of console application<masterz>\n"); HANDLE hThread = CreateThread( NULL, // no security attributes 0, // use default stack size Thread, // thread function 0, // argument to thread function 0, // use default creation flags &dwThreadId); DWORD dwwait=WaitForSingleObject(hThread,1000*30); switch(dwwait) { case WAIT_ABANDONED: printf("main thread WaitForSingleObject return WAIT_ABANDONED\n"); break; case WAIT_OBJECT_0: printf("main thread WaitForSingleObject return WAIT_OBJECT_0\n"); break; case WAIT_TIMEOUT: printf("main thread WaitForSingleObject return WAIT_TIMEOUT\n"); break; } CloseHandle(hThread); _getch(); } unsigned long WINAPI Thread(PVOID pvoid) { MSG msg; PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); UINT timerid=SetTimer(NULL,111,3000,NULL); BOOL bRet; int count =0; while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { if (bRet == -1) { // handle the error and possibly exit } else if(msg.message==WM_TIMER) { count++; printf("WM_TIMER in work thread count=%d\n",count); if(count>4) break; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } KillTimer(NULL,timerid); printf("thread end here\n"); return 0; }