question

drjackool-3839 avatar image
0 Votes"
drjackool-3839 asked PengGe-MSFT edited

How set timer in worker thread

Hi
In Win32 app/MFC
Is there a way to set a timer like SetTimer() function for a window but for a working thread that not have a window?

Thanks

windows-api
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RLWA32-6355 avatar image
0 Votes"
RLWA32-6355 answered

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);
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.