最近想寫一個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 原文作者:洞庭散人