2,784 questions
You an use SetTimer in an MFC worker thread but it must have a message pump even though it doesn't create windows. For example -
#pragma once
// CTimerThread
class CTimerThread : public CWinThread
{
DECLARE_DYNCREATE(CTimerThread)
protected:
CTimerThread(); // protected constructor used by dynamic creation
virtual ~CTimerThread();
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
static VOID CALLBACK TimerProc(HWND hwnd, UINT msg, UINT_PTR uintId, DWORD dwTime);
protected:
DECLARE_MESSAGE_MAP()
public:
UINT_PTR m_TimerId;
DWORD m_Interval;
};
Implementation -
// CTimerThread.cpp : implementation file
//
#include "pch.h"
#include "CTimerThread.h"
// CTimerThread
IMPLEMENT_DYNCREATE(CTimerThread, CWinThread)
VOID CALLBACK CTimerThread::TimerProc(HWND hwnd, UINT msg, UINT_PTR uintId, DWORD dwTime)
{
TRACE(_T("In %s\n"), _T(__FUNCTION__));
}
CTimerThread::CTimerThread()
{
m_TimerId = 0;
m_Interval = 1000;
}
CTimerThread::~CTimerThread()
{
}
BOOL CTimerThread::InitInstance()
{
// TODO: perform and per-thread initialization here
m_TimerId = SetTimer(NULL, 0, m_Interval, CTimerThread::TimerProc);
return TRUE;
}
int CTimerThread::ExitInstance()
{
// TODO: perform any per-thread cleanup here
ASSERT(KillTimer(NULL, m_TimerId));
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(CTimerThread, CWinThread)
END_MESSAGE_MAP()
// CTimerThread message handlers
Start and stop the thread from an MFC dialog based application -
void CMFCWorkTimerDlg::OnBnClickedStart()
{
// TODO: Add your control notification handler code here
m_pTimerThread = AfxBeginThread(RUNTIME_CLASS(CTimerThread));
}
void CMFCWorkTimerDlg::OnBnClickedStop()
{
// TODO: Add your control notification handler code here
PostThreadMessage(m_pTimerThread->m_nThreadID, WM_QUIT, 0, 0);
}