Windows应用程序的消息处理机制

来源:互联网 发布:php curl 超时处理 编辑:程序博客网 时间:2024/06/05 03:46

Windows应用程序的消息处理机制:

这里写图片描述

1)操作系统接收应用程序窗口信息,将消息传递到应用程序的消息队列中;
2)应用程序在消息循环中,调用GetMessage函数,将消息从队列中一条一条取出来,并进行预处理;
3)应用程序调用DispatchMessage, 将消息传递会给操作系统;
4)操作系统调用窗口过程函数,对消息进行处理(即“系统给应用程序发送了消息”);

实例:

#include <windows.h>#include <stdio.h>LRESULT CALLBACK WinSunProc(    HWND hwnd,    UINT uMsg,    WPARAM wParam,    LPARAM lParam);int WINAPI WinMain(    HINSTANCE hInstance,    HINSTANCE hPrevInstance,    LPSTR lpCmdLine,    int nCmdShow){    //设计一个窗口    WNDCLASS wndcls;    wndcls.cbClsExtra = 0;    wndcls.cbWndExtra = 0;    wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);    wndcls.hCursor = LoadCursor(NULL,IDC_CROSS);    wndcls.hIcon = LoadIcon(NULL,IDI_ERROR);    wndcls.hInstance = hInstance;    wndcls.lpfnWndProc = WinSunProc;    wndcls.lpszClassName = "sunxin2006";    wndcls.lpszMenuName = NULL;    wndcls.style = CS_HREDRAW | CS_VREDRAW;    //注册    RegisterClass(&wndcls);    //创建一个窗口    HWND hwnd;    hwnd = CreateWindow("sunxin2006","http://www.sunxin.org",WS_OVERLAPPEDWINDOW,0,0,600,400,NULL,NULL,hInstance,NULL);    //显示及刷新窗口    ShowWindow(hwnd,SW_SHOWNORMAL);    UpdateWindow(hwnd);    //定义消息结构体,开始消息循环    MSG msg;    while(GetMessage(&msg,hwnd,0,0))    {        TranslateMessage(&msg);        DispatchMessage(&msg);    }    return msg.wParam;}//编写窗口过程函数LRESULT CALLBACK WinSunProc(  HWND hwnd,  UINT uMsg,  WPARAM wParam,  LPARAM lParam ){    switch(uMsg)    {    case WM_CHAR:        char szChar[20];        sprintf(szChar,"char code is %d",wParam);        MessageBox(hwnd,szChar,"char",0);        break;    case WM_LBUTTONDOWN:        MessageBox(hwnd,"mouse clicked","message",0);        HDC hdc;        hdc = GetDC(hwnd);        TextOut(hdc,0,50,"程序员之家",strlen("程序员之家"));        break;    case WM_PAINT:        HDC hDc;        PAINTSTRUCT ps;        hDc = BeginPaint(hwnd,&ps);        TextOut(hDc,0,0,"http://www.sunxin.org",strlen("http://www.sunxin.org"));        EndPaint(hwnd,&ps);        break;    case WM_DESTROY:        PostQuitMessage(0);        break;    default:        return DefWindowProc(hwnd,uMsg,wParam,lParam);    }    return 0;}
0 0
原创粉丝点击