Thread and Timer
Hi,
I'd like to use a timer inside a thread (CWinThread derived class).
If I use the CALLBACK procedure I get the timer, if I don't use the
CALLBACK and handle in OnTimer I never get the message.
Here is the code:
// WatchDog.cpp : implementation file
//
#include "stdafx.h"
#include "xcrashreport.h"
#include "WatchDog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CString g_sFileName;
HWND g_hWnd;
UINT g_iMessage;
UINT g_iTimer;
UINT g_iTimerTimeout;
/////////////////////////////////////////////////////////////////////////////
// CWatchDog
void CALLBACK OnTimerProc(
HWND hwnd, // handle to window
UINT uMsg, // WM_TIMER message
UINT_PTR idEvent, // timer identifier
DWORD dwTime // current system time
)
{ // OnTimerProc
if (idEvent == g_iTimer)
{
PostMessage(g_hWnd, g_iMessage, WPARAM (0), LPARAM (0));
KillTimer( NULL, g_iTimer );
AfxEndThread( 0, false );
}
} // OnTimerProc
IMPLEMENT_DYNCREATE(CWatchDog, CWinThread)
BOOL CWatchDog::InitInstance()
{
// TODO: perform and per-thread initialization here
return TRUE;
}
int CWatchDog::ExitInstance()
{
// TODO: perform any per-thread cleanup here
return CWinThread::ExitInstance();
}
BOOL CWatchDog::IsIdleMessage( MSG* pMsg )
{
if ( !CWinThread::IsIdleMessage( pMsg ) || ( pMsg->message ==
WM_TIMER ) )
{
return FALSE;
}
return TRUE;
}
BEGIN_MESSAGE_MAP(CWatchDog, CWinThread)
//{{AFX_MSG_MAP(CWatchDog)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
ON_THREAD_MESSAGE(WM_TIMER, OnTimer)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWatchDog message handlers
void CWatchDog::Monitor(CString sFileName, HWND hWnd, UINT iMessage,
int iFrequency, int iTimeout)
{
//g_iTimer = ::SetTimer(NULL, NULL, iFrequency, (TIMERPROC)
OnTimerProc);
g_iTimer = SetTimer(NULL, 0, iFrequency, NULL);
g_hWnd = hWnd;
g_iMessage = iMessage;
}
void CWatchDog::OnTimer(WPARAM wParam, LPARAM lParam)
{
if ((UINT) wParam == g_iTimer)
{
PostMessage(g_hWnd, g_iMessage, WPARAM (0), LPARAM (0));
}
}
Thanks in advance,
Stefano