C++定时器

来源:互联网 发布:在淘宝上开店靠谱吗 编辑:程序博客网 时间:2024/06/07 02:29

//方式一


#include <iostream>  

#include <Windows.h>  


using namespace std;  

void CALLBACK TimeProc(HWND hwnd,UINT message,UINT idTimer,DWORD dwTime);  


int   main(int argc, char * argv[])  
{  
SetTimer(NULL,1,1000,TimeProc);  




MSG msg;  
while (GetMessage(&msg,NULL,0,0))  
{  
if (msg.message == WM_TIMER)  
{  
DispatchMessage(&msg);  
}  
}  
return 0;  
}  


int ncount = 0;  
void CALLBACK TimeProc(HWND hwnd,UINT message,UINT idTimer,DWORD dwTime)  
{  
cout << "\r" << ncount++<<flush; 
}  




方式二


#include <Windows.h>  
#include <iostream>
using namespace  std;



int ncount = 0;  


void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT_PTR idEvent,DWORD dwTime)  
{  
    if (nMsg== WM_TIMER)
    {
  cout << "\r" << ncount++<<flush; 
    } 
}  


DWORD CALLBACK    ThreadFun(PVOID pvoid)  
{  

UINT timerid = SetTimer(NULL,1,1000,TimerProc);  

MSG msg;  
 
BOOL bRet;  
//阻塞等待消息到来
while ((bRet = GetMessage(&msg,NULL,0,0)) != 0)  
{  
if (bRet == -1)  
{   
  cout<<"error:"<<GetLastError()<<endl;  
break;  
}  
else  
{  
TranslateMessage(&msg);  
DispatchMessage(&msg);  
}  
}  


//KillTimer(NULL,timerid);  
cout<<"thread end here!"<<endl;  
return 0;  


}  


int  main(int argc, char * argv[])  
{  
HANDLE hThread = CreateThread(NULL,0,ThreadFun,NULL,0,NULL);  
getchar();  
return 0;  
}  



方式三(不精准)


#include <Windows.h>  
#include <iostream>
using namespace  std;


int  ncount=0;


DWORD    WINAPI   ThreadFun(LPVOID pama)
{
UINT oldTickCount  = GetTickCount();


while(TRUE)
{  
while(TRUE)
{
UINT  newTickCount = GetTickCount();
if(newTickCount - oldTickCount >= 1000)
{
oldTickCount = newTickCount;
break;
}
}
 
//代码
 cout << "\r" << ncount++<<flush; 


}
return 0; 
}


int  main(int argc, char * argv[])  
{  


HANDLE hThread = CreateThread(NULL,0,ThreadFun,NULL,0,NULL);  




getchar();  
return 0;  
}