zoukankan      html  css  js  c++  java
  • Win32控制台中使用定时器

        最近想写一个Win32控制台版的贪食蛇,需要用到定时器,在MFC中编程很方便的用OnTimer()函数就可以实现定时中断函数的编写,玩单片机的时候也可以写个定时器中断,现在在Win32控制台中编程没有消息循环,MSDN里也不推荐把SetTimer()用在Console Applications里,于是在网上索罗了一下,发现一个在线程中创建定时器,再通过指定的回调函数来处理定时器触发的方法挺不错的,以下是测试代码,在VC6.0中调试通过。

     1 #include <stdio.h>
     2 #include <windows.h>
     3 #include <conio.h>
     4 
     5 UINT cnt = 0;
     6 
     7 // 定时器回调函数
     8 void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);
     9 // 线程回调函数
    10 DWORD CALLBACK ThreadProc(PVOID pvoid);  
    11 
    12 // 主函数
    13 int main()
    14 {
    15     DWORD dwThreadId;
    16     // 创建线程
    17     HANDLE hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThreadId); 
    18     printf("hello, thread start!\n");
    19     getch();       // 得到键盘输入后再退出
    20     return 0;
    21 }    
    22 
    23 void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
    24 {
    25     cnt ++;
    26     printf("thread count = %d\n", cnt);
    27 }
    28 
    29 DWORD CALLBACK ThreadProc(PVOID pvoid)
    30 {
    31     MSG msg;
    32     PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); 
    33     SetTimer(NULL, 10, 1000, TimeProc);
    34     while(GetMessage(&msg, NULL, 0, 0))
    35     {
    36         if(msg.message == WM_TIMER)
    37         {
    38             TranslateMessage(&msg);    // 翻译消息
    39             DispatchMessage(&msg);     // 分发消息
    40         }
    41     }
    42     KillTimer(NULL, 10);
    43     printf("thread end here\n");
    44     return 0;
    45 }

    参考自:http://www.cnblogs.com/phinecos/archive/2008/03/08/1096691.html  原文作者:洞庭散人

  • 相关阅读:
    Python字符串
    MySQL触发器
    MySQL 1418报错解决办法
    数据库下载
    补码与反码
    二、八、十六进制之间的转换
    this 指向
    作用域 var 词法分析 arguments
    事件绑定的3种方式
    清浮动方法小结
  • 原文地址:https://www.cnblogs.com/imapla/p/2663215.html
Copyright © 2011-2022 走看看