代码改变世界

消息处理相关

2011-04-28 23:26  Clingingboy  阅读(567)  评论(0编辑  收藏  举报

 

一.PostMessage和SendMessage

SendMessage,PostMessage: 前者同步,后者异步其他没有区别。 (还不确定)

参考:http://zhidao.baidu.com/question/56113426.html
http://topic.csdn.net/u/20100818/02/65ef56ca-e41b-4909-9c1b-8fd2a81710e7.html

二.PostThreadMessage

用于线程通信

参考:http://blog.csdn.net/zyq5945/archive/2009/12/09/4971431.aspx
http://www.newsmth.net/pc/pccon.php?id=1451&nid=200311

三.RegisterWindowMessage

用于自定义消息,如果调用此函数,则会在系统中添加一个注册的标识,如果成功则返回TRUE,失败则返回FALSE.如果不用此函数注册的话,可能会发生重复消息冲突的问题

#define UM_MSG1 WM_USER+1
#define UM_MSG2 WM_USER+2

参考

#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <process.h>
#define UM_MSG1 WM_USER+1
#define UM_MSG2 WM_USER+2
using namespace std;
DWORD WINAPI Thread1(LPVOID para)
{
    
    DWORD dwThreadId = *(DWORD *)para;
    DWORD i=0;
    TCHAR *p;
    char strTmp[100];
    
    while(TRUE)
    {
        
        Sleep(1700);        
        p=new TCHAR[10];
        sprintf(strTmp,"Hello %d %x",i++,p);
        printf("Thread1:\t%s0\n",strTmp);
        PostThreadMessage(dwThreadId,UM_MSG1,(WPARAM)strTmp,(LPARAM)p);
        //delete []p;
    }
    
    return 0;    
    
}
DWORD WINAPI Thread2(LPVOID para)
{
    
    char strTmp[100];
    DWORD dwThreadId = *(DWORD *)para;
    DWORD i=0;
    TCHAR *p;
    while(TRUE)
    {
        
        Sleep(3000);
        p=new TCHAR[10];
        sprintf(strTmp,"World %d %x",i++,p);
        printf("Thread2:\t%s0\n",strTmp);
        PostThreadMessage(dwThreadId,UM_MSG2,(WPARAM)strTmp,(LPARAM)p);
        //delete []p;
    }
    
    return 0;
    
}
int main()
{
    
    DWORD dwValue =GetCurrentThreadId();
    cout<<"GetCurrentThreadId "<<dwValue<<endl;;
    HANDLE hThread1 = CreateThread(NULL,0,&Thread1,&dwValue,0,NULL);
    HANDLE hThread2 = CreateThread(NULL,0,&Thread2,&dwValue,0,NULL);
    CloseHandle(hThread1);
    CloseHandle(hThread2);
    MSG msg;
    while(GetMessage(&msg,NULL,0,0))
    {
        switch(msg.message)
        {
        case UM_MSG1:
        case UM_MSG2:
            printf("msg:0x%x \t%x \t%s0\n",msg.message,msg.lParam,msg.wParam);
            //注释掉这句你就会看到堆内存地址变化
            delete [](TCHAR *)msg.lParam;  
            break;
        default:
            printf("Unknown msg:0x%x\n",msg.message);
            break;
        }
        Sleep(1);
    }
    return 0;
} 




四.关于WM_PAINT重绘的问题

WM_PAINT总是被排在消息队列的队尾,可减少UI重绘的次数,比如一个Button同时改变高度和宽度,那么消息如果是 ChangeWidth->Paint=>ChangeHeight=>Paint,就重绘了两次,Paint排最后的话则是
ChangeWidth->ChangeHeight=>Paint,节省了一次重绘的时间

参考:http://wenku.baidu.com/view/0eb7330102020740be1e9b90.html 很好的资料

五.GetMessagePos

The return value specifies the x- and y-coordinates of the cursor position. The x-coordinate is the low order short and the y-coordinate is the high-order short.