在MFC中用OnTimer()函數就可以很方便的實現定時事件,但在Win32控制台工程中沒有消息循環,MSDN里也不推薦把SetTimer()用在Console Applications里。
同理,在DLL工程中創建定時器也需用這種方法,因為DLL沒有窗口,沒窗口就沒有消息循環,沒消息循環就收到不到定時消息。如果DLL有窗口的話,就可以在SetTimer()時指定窗口句柄也行,直接用GetForegroundWindow()得到句柄。
方法:在一個單獨的線程中創建定時器,再通過指定的回調函數來處理定時事件。
- #include <stdio.h>
- #include <windows.h>
- #include <conio.h>
- UINT cnt = 0;
- //定時器回調函數
- void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);
- //線程回調函數
- DWORD CALLBACK ThreadProc(PVOID pvoid);
- //主函數
- int main()
- {
- //創建線程
- DWORD dwThreadId;
- HANDLE hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThreadId);
- printf("hello, thread start!\n");
- //得到鍵盤輸入后再退出
- getch();
- return 0;
- }
- //線程
- DWORD CALLBACK ThreadProc(PVOID pvoid)
- {
- //強制系統為線程簡歷消息隊列
- MSG msg;
- PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
- //設置定時器
- SetTimer(NULL, 10, 1000, TimeProc);
- //獲取並分發消息
- while(GetMessage(&msg, NULL, 0, 0))
- {
- if(msg.message == WM_TIMER)
- {
- TranslateMessage(&msg); // 翻譯消息
- DispatchMessage(&msg); // 分發消息
- }
- }
- KillTimer(NULL, 10);
- printf("thread end here\n");
- return 0;
- }
- //定時事件
- void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
- {
- cnt ++;
- printf("thread count = %d\n", cnt);
- }
#include <stdio.h>
#include <windows.h>
#include <conio.h>
UINT cnt = 0;
//定時器回調函數
void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);
//線程回調函數
DWORD CALLBACK ThreadProc(PVOID pvoid);
//主函數
int main()
{
//創建線程
DWORD dwThreadId;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &dwThreadId);
printf("hello, thread start!\n");
//得到鍵盤輸入后再退出
getch();
return 0;
}
//線程
DWORD CALLBACK ThreadProc(PVOID pvoid)
{
//強制系統為線程簡歷消息隊列
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
//設置定時器
SetTimer(NULL, 10, 1000, TimeProc);
//獲取並分發消息
while(GetMessage(&msg, NULL, 0, 0))
{
if(msg.message == WM_TIMER)
{
TranslateMessage(&msg); // 翻譯消息
DispatchMessage(&msg); // 分發消息
}
}
KillTimer(NULL, 10);
printf("thread end here\n");
return 0;
}
//定時事件
void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{
cnt ++;
printf("thread count = %d\n", cnt);
}
jpg改rar

