WEB开发网
开发学院软件开发VC 通过异步程序调用(APC)实现的定时功能 阅读

通过异步程序调用(APC)实现的定时功能

 2006-07-20 11:42:45 来源:WEB开发网   
核心提示: 【示例代码】#define _WIN32_WINNT 0x0500#include <windows.h>#include <stdio.h>#define _SECOND 10000000typedef struct _MYDATA { TCHAR *szText

【示例代码】

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#define _SECOND 10000000
typedef struct _MYDATA {
  TCHAR *szText;
  DWORD dwValue;
} MYDATA;
VOID CALLBACK TimerAPCProc(
  LPVOID lpArg,        // Data value
  DWORD dwTimerLowValue,   // Timer low value
  DWORD dwTimerHighValue )  // Timer high value
{
  MYDATA *pMyData = (MYDATA *)lpArg;
  printf( "Message: %s\nValue: %d\n\n", pMyData->szText,
     pMyData->dwValue );
  MessageBeep(0);
}
void main( void )
{
  HANDLE     hTimer;
  BOOL      bSuccess;
  __int64     qwDueTime;
  LARGE_INTEGER  liDueTime;
  MYDATA     MyData;
  TCHAR      szError[255];
  MyData.szText = "This is my data.";
  MyData.dwValue = 100;
  if ( hTimer = CreateWaitableTimer(
      NULL,          // Default security attributes
      FALSE,         // Create auto-reset timer
      "MyTimer" ) )      // Name of waitable timer
  {
   __try
   {
     // Create an integer that will be used to signal the timer
     // 5 seconds from now.
     qwDueTime = -5 * _SECOND;
     // Copy the relative time into a LARGE_INTEGER.
     liDueTime.LowPart = (DWORD) ( qwDueTime & 0xFFFFFFFF );
     liDueTime.HighPart = (LONG) ( qwDueTime >> 32 );
     bSuccess = SetWaitableTimer(
      hTimer,      // Handle to the timer object
      &liDueTime,    // When timer will become signaled
      2000,       // Periodic timer interval of 2 seconds
      TimerAPCProc,   // Completion routine
      &MyData,     // Argument to the completion routine
      FALSE );     // Do not restore a suspended system
     if ( bSuccess )
     {
      for ( ; MyData.dwValue < 1000; MyData.dwValue += 100 )
      {
        SleepEx(
         INFINITE,   // Wait forever
         TRUE );    // Put thread in an alertable state
      }
     }
     else
     {
      wsprintf( szError, "SetWaitableTimer failed with Error \
        %d.", GetLastError() );
      MessageBox( NULL, szError, "Error", MB_ICONEXCLAMATION );
     }
   }
   __finally
   {
     CloseHandle( hTimer );
   }
  }
  else
  {
   wsprintf( szError, "CreateWaitableTimer failed with Error %d.",
     GetLastError() );
   MessageBox( NULL, szError, "Error", MB_ICONEXCLAMATION );
  }
}

原文参考:Using a Waitable Timer with an Asynchronous Procedure Call

上一页  1 2 3 

Tags:通过 异步 程序

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接