//#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <stdlib.h>
#pragma comment(lib,"Winmm.lib")
#define delaytime 1000
int gtime_ID;
void CALLBACK TimeEvent(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
printf("time ID is %d, started,dwUser is %d\n",gtime_ID, dwUser);
return;
}
void StartEventTime(DWORD_PTR duser)
{
gtime_ID = timeSetEvent(delaytime,10,(LPTIMECALLBACK)TimeEvent,duser,TIME_PERIODIC);
if(gtime_ID == NULL)
{
printf("time ID is not created\n");
return;
}
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
while (1)
{
StartEventTime(i);
Sleep(1100);
i++;
timeKillEvent(gtime_ID);
if (i == 10)
{
break;
}
}
return 0;
}
#include <windows.h>
#include <iostream>
using namespace std;
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{
cout << "Time: " << dwTime << '\n'<<endl;
}
int main(int argc, char *argv[])
{
int Counter=0;
MSG Msg;
UINT TimerId = SetTimer(NULL, 0, 5000, &TimerProc);
cout << "TimerId: " << TimerId << '\n';
if (!TimerId)
{
return 16;
}
while (GetMessage(&Msg, NULL, 0, 0))
{
++Counter;
if (Msg.message == WM_TIMER)
{
cout << "Counter: " << Counter << "; timer message\n";
}
else
{
cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
}
DispatchMessage(&Msg);
}
KillTimer(NULL, TimerId);
return 0;
}
#include <windows.h>
#include <iostream>
using namespace std;
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{
cout << "Time: " << dwTime << '\n'<<endl;
}
int main(int argc, char *argv[])
{
int Counter=0;
MSG Msg;
UINT TimerId = SetTimer(NULL, 0, 3000, &TimerProc);
cout << "TimerId: " << TimerId << '\n';
if (!TimerId)
{
return 16;
}
while(1)
{
if (PeekMessage (&Msg, NULL, 0, 0, PM_REMOVE))
{
++Counter;
if (Msg.message == WM_TIMER)
{
cout << "Counter: " << Counter << "; timer message\n";
}
else
{
cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
}
DispatchMessage(&Msg);
if (Msg.message == WM_QUIT)
{
KillTimer(NULL, TimerId);
return 0;
}
}
}
}
PeekMessage和GetMessage函数的主要区别有:
1. GetMessage的主要功能是从消息队列中“取出”消息,消息被取出以后,就从消息队列中将其删除;而PeekMessage的主要功能是“窥视”消息,如果有消息,就返回true,否则返回false。也可以使用PeekMessage从消息队列中取出消息,这要用到它的一个参数(UINT wRemoveMsg),如果设置为PM_REMOVE,消息则被取出并从消息队列中删除;如果设置为PM_NOREMOVE,消息就不会从消息队列中取出。
2. 如果GetMessage从消息队列中取不到消息,则线程就会被操作系统挂起,等到OS重新调度该线程时,两者的性质不同:使用GetMessage线程仍会被挂起,使用PeekMessage线程会得到CPU的控制权,运行一段时间。
3. GetMessage每次都会等待消息,直到取到消息才返回;而PeekMessage只是查询消息队列,没有消息就立即返回,从返回值判断是否取到了消息。
我们也可以说,PeekMessage是一个具有线程异步行为的函数,不管消息队列中是否有消息,函数都会立即返回。而GetMessage则是一个具有线程同步行为的函数,如果消息队列中没有消息的话,函数就会一直等待,直到消息队列中至少有一条消息时才返回。
如果消息队列中没有消息,PeekMessage总是能返回,这就相当于在执行一个循环,如果消息队列一直为空, 它就进入了一个死循环。GetMessage则不可能因为消息队列为空而进入死循环。