C++控制台程式中使用定時器

來源:互聯網
上載者:User

轉自部落格:http://www.cnblogs.com/phinecos/archive/2008/03/08/1096691.html
作者:洞庭散人

“我現在項目是一個控制台程式,用到的Win32API都是與介面無關的,今天需要加入定時器重新整理的功能,由於沒有訊息迴圈,所以WM_TIMER訊息應該如何處理呢?綜合了下網上找到的資料,寫了個簡單的demo,個人以為這種在一個線程中建立定時器,再通過指定的回呼函數來處理定時器觸發的模式是比較好的。”

demo:

 

#include <Windows.h>
#include <stdio.h>
#include <conio.h>

 

int count = 0;

 

void CALLBACK TimerProc(HWND hWnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
{
 count++;
 printf("WM_TIMER in work thread count=%d/n",count);
}

 

DWORD CALLBACK Thread(PVOID pvoid)
{
 MSG 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;
};

 

本人在瞭解了作者的意圖以後,也做了一個類封裝:

#include <Windows.h>
#include <stdio.h>
#include <conio.h>

class CTimer
{
public:
 CTimer();
 void CreateTimerThread(int* pi);
 static DWORD CALLBACK TimeThread(PVOID pvoid);
 static void CALLBACK TimeProc(HWND 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 pvoid)
{
 int* pi = (int*)pvoid;
 int itm = *pi;
 MSG 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 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;
};

 

感謝洞庭散人...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.