控制檯程式實現Timer

Awey_001發表於2010-10-19

#include <windows.h>
#include <stdio.h>
#include <conio.h>
DWORD WINAPI Thread_Timer(PVOID pvoid);
void main()
{
 DWORD dwThreadId;
 printf("use timer in workthread of console application <masterz>/n");
 HANDLE hThread = CreateThread(NULL,0,Thread_Timer,0,0,&dwThreadId);
 DWORD dwwait=WaitForSingleObject(hThread,1000*30);
 switch(dwwait)
 {
  case WAIT_ABANDONED:
   printf( "main thread WaitForSingleObject return WAIT_ABANDONED/n");
   break;
  case WAIT_OBJECT_0:
   printf( "main thread WaitForSingleObject return WAIT_OBJECT_0/n");
   break;
  case WAIT_TIMEOUT:
   printf( "main thread WaitForSingleObject return WAIT_TIMEOUT/n");
   break;
 }
 CloseHandle(hThread);
 _getch();
}

DWORD WINAPI Thread_Timer(PVOID pvoid)
{
 MSG msg;
 PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
 UINT timerid=SetTimer(NULL,1,1000,NULL);
 BOOL bRet;
 int count = 0;
 while((bRet = GetMessage(&msg,NULL,0,0)) != 0)
 {
  if(bRet == -1)
  {
  }
  else
   if(msg.message == WM_TIMER)
   {
    count++;
    printf("WM_TIMER in work thread count=%d/n",count);
    if(count > 4)
    break;
   }
   else
   {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
   }
 }
 KillTimer(NULL,timerid);
 printf("thread end here/n");
 return 0;
}

原文:http://topic.csdn.net/t/20040509/14/3045648.html

相關文章