测试WM_TIMER 消息 以及计时器

来源:互联网 发布:美墨边境 知乎 编辑:程序博客网 时间:2024/05/20 18:18

/*
 名称 Timer
 功能:每产生一个WM_TIMER消息则屏幕变换一次颜色.
 目的:测试WM_TIMER 消息 以及计时器。
*/

#include <windows.h>#define ID_TIMER 1LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,LPARAM lParam);LRESULT CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT iTimerID,DWORD dwTime);int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,        LPSTR lpCmdLine, int nCmdShow)    { WNDCLASS wndcls; MSG   msg; HWND  hwnd; TCHAR  szClassName[] = TEXT("Myclass");  wndcls.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS; wndcls.lpfnWndProc = WindowProc; wndcls.cbClsExtra = 0; wndcls. cbWndExtra = 0; wndcls. hInstance = hInstance; wndcls. hIcon =LoadIcon(NULL,IDI_APPLICATION);  wndcls.hCursor = LoadCursor(NULL,IDC_ARROW); wndcls. hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); wndcls.lpszMenuName =NULL; wndcls.lpszClassName = szClassName; RegisterClass(&wndcls); hwnd = CreateWindow(szClassName,"Timer demo ",WS_OVERLAPPEDWINDOW ,  CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,  NULL,NULL,hInstance,NULL); ShowWindow(hwnd,nCmdShow); UpdateWindow(hwnd); while(GetMessage(&msg,NULL,0,0)) {  TranslateMessage(&msg);  DispatchMessage(&msg); } return msg.wParam;}LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,LPARAM lParam){ switch (uMsg) { case WM_CREATE:  {   SetTimer(hwnd,ID_TIMER,1000,TimerProc);   return 0;  } case WM_DESTROY:  {   KillTimer(hwnd,ID_TIMER);   PostQuitMessage(0);   return 0;  } } return DefWindowProc(hwnd,uMsg,wParam,lParam);}LRESULT CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT iTimerID,DWORD dwTime){ HDC hdc; PAINTSTRUCT pt; HBRUSH  hBrush; RECT  rect; static BOOL  IsPaint = FALSE;    //static 作用?如果没有它,该城市将得不到想要的效果 MessageBeep (-1) ;           IsPaint = !IsPaint; hdc = GetDC(hwnd); GetClientRect(hwnd,&rect); hBrush = CreateSolidBrush(IsPaint ? RGB(255,0,0) : RGB(0,0,255));    //注意 FillRect(hdc,&rect,hBrush); ReleaseDC(hwnd,hdc); DeleteObject(hBrush);}


 

/*
   1.windows 直接将WM_TIMER 消息发送到 TimerProc函数去处理,
  像其他窗口过程一样刺函数也必须定义成CALLBACK,因为他是window本
  身要呼叫的,
   2.CALLBACK 函数的参数和返回值取决于CALLBACK函数的目的。
  WM_TIMER函数的参数和WindowProc的参数相同,WM_TIMER不需要返
  回值。
   3.当您使用 CALLBACK 函数 处理WM_TIMER消息时呼叫
  SetTimer(hwnd,ID_TIMER,1000,TimerProc);  注意最后一个参数!
  在这以后所有WM_TIMER消息都会发送给TimerProc函数.
   4.static 的用法? 本程序如果修改该参数,则得不到该有的效果。

                    2012.07.20  21:13:50
  
*/