Blog: http://www.cnblogs.com/phinecos/archive/2008/03/08/1096691.html
Author: Dongting sangren
"My current project is a console program, and the WIN32API used is irrelevant to the interface. Today we need to add the timer refresh function. Since there is no message loop, how should we handle the wm_timer message? Based on the information found on the internet, I wrote a simple demo. I thought this was the way to create a timer in a thread, it is better to use the specified callback function to process the timer-triggered mode."
Demo:
# Include <windows. h>
# Include <stdio. h>
# Include <conio. h>
Int COUNT = 0;
Void callback timerproc (hwnd, uint umsg, uint_ptr idevent, DWORD dwtime)
{
Count ++;
Printf ("wm_timer in work thread count = % d/N", count );
}
DWORD callback thread (pvoid)
{
MSG;
Peekmessage (& MSG, null, wm_user, wm_user, pm_noremove );
Uint timerid = settimer (null, 111,3000, timerproc );
Bool Bret;
While (Bret = getmessage (& MSG, null, 0, 0 ))! = 0)
{
If (Bret =-1)
{
Printf ("error: the thread will quit, error ID is % d/N", getlasterror ());
Break;
}
Else
{
Translatemessage (& MSG );
Dispatchmessage (& MSG );
}
}
Killtimer (null, timerid );
Printf ("thread end here/N ");
Return 0;
}
Int main ()
{
DWORD dwthreadid;
Printf ("use timer in workthread of console application/N ");
Handle hthread = createthread (null, 0, thread, null, 0, null );
_ Getch ();
Return 0;
};
After understanding the author's intention, I also made a class encapsulation:
# Include <windows. h>
# Include <stdio. h>
# Include <conio. h>
Class ctimer
{
Public:
Ctimer ();
Void createtimerthread (int * PI );
Static DWORD callback timethread (pvoid );
Static void callback timeproc (hwnd, uint umsg, uint_ptr idevent, DWORD dwtime );
};
Ctimer: ctimer ()
{
}
Void ctimer: createtimerthread (int * PI)
{
Handle hand = createthread (null, 0, ctimer: timethread, PI, 0, null );
}
DWORD callback ctimer: timethread (pvoid)
{
Int * Pi = (int *) pvoid;
Int ITM = * PI;
MSG;
Peekmessage (& MSG, null, wm_user, wm_user, pm_noremove );
Uint timeid = settimer (null, 111, ITM, ctimer: timeproc );
Bool Bret;
While (Bret = getmessage (& MSG, null, 0, 0 ))! = 0)
{
If (Bret =-1)
{
Printf ("error: the thread will quit, error ID is % d/N", getlasterror ());
Break;
}
Else
{
Translatemessage (& MSG );
Dispatchmessage (& MSG );
}
}
Killtimer (null, timeid );
Printf ("thread end here/N ");
Return 0;
}
Void callback ctimer: timeproc (hwnd, uint umsg, uint_ptr idevent, DWORD dwtime)
{
Printf ("wm_timer in work thread count/N ");
}
Int main ()
{
Int itime = 1000;
Int * Pi = & itime;
Ctimer * ptime = new ctimer;
Ptime-> createtimerthread (PI );
_ Getch ();
Return 0;
};
Thank you for being an individual in Dongting...