邢红瑞的blog--如何在控制台程序中使用定时器

导读:
  这是一个看似简单,但是很复杂的问题,因为windows使用WM_TIMER,但是console下没有Hwnd,没有消息分发器,不象unix下可以用alarm信号定时执行某个函数,不知道java是如何实现的。
  想起masterz曾经给出过例子,自从做java后,再也没有见过他。其实这个也不难,但首先要保证你的定时器要在一个线程中设置,如果你用MFC,那么在控制台中你可以从CWinThread派生一个类,然后在这个类中设置定时器,但不像CWnd类中的定时器那么好用。
  user timer in workthread of console app
  #include
  #include
  #include
  unsigned long WINAPI Thread(PVOID pvoid);
  void main()
  {
  DWORD dwThreadId;
  printf("use timer in workthread of console application /n");
  HANDLE hThread = CreateThread(
  NULL, // no security attributes
  0, // use default stack size
  Thread, // thread function
  0, // argument to thread function
  0, // use default creation flags
  &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();
  }
  
  unsigned long WINAPI Thread(PVOID pvoid)
  {
  MSG msg;
  PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
  UINT timerid=SetTimer(NULL,111,3000,NULL);
  BOOL bRet;
  int count =0;
  while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
  {
  if (bRet == -1)
  {
  // handle the error and possibly exit
  }
  else
  if(msg.message==WM_TIMER)
  {
  count++;
  printf("WM_TIMER in work thread count=%d/n",count);
  if(count>4)
  break;
  }
  else
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值