如何向窗口发送消息

来源:互联网 发布:大数据统计学就业前景 编辑:程序博客网 时间:2024/05/08 18:24

CWnd类的SendMessage和PostMessage成员函数.

第一步:在头文件中自定义消息,如:

#define WM_USER_MSG (WM_USER +100)

第二步:通过类向导点击Message选项卡,添加自定义消息WM_USER_MSG.

第三步:实现自定义消息的响应函数.

第四步:发送消息.

发送消息有两种方式.

1 同步发送(SendMessage)

LRESULT SendMessage(   UINT message,   WPARAM wParam = 0,   LPARAM lParam = 0 );

message:消息ID.

wParam:参数1

lParam:参数2

返回值:消息函数函数的处理结果.

这里同步发送是指发送消息并处理完后才返回.如:

http://msdn.microsoft.com/en-US/library/t64sseb3(v=vs.80)

// In a dialog-based app, if you add a minimize button to your // dialog, you will need the code below to draw the icon.void CMyDlg::OnPaint() {   if (IsIconic())   {      CPaintDC dc(this); // device context for painting      SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);      // Center icon in client rectangle      int cxIcon = GetSystemMetrics(SM_CXICON);      int cyIcon = GetSystemMetrics(SM_CYICON);      CRect rect;      GetClientRect(&rect);      int x = (rect.Width() - cxIcon + 1) / 2;      int y = (rect.Height() - cyIcon + 1) / 2;      // Draw the icon represented by handle m_hIcon      dc.DrawIcon(x, y, m_hIcon);   }   else   {      CDialog::OnPaint();   }}

MSDN中对SendMessage解说如下:

The SendMessage member function calls the window procedure directly and does not return until that window procedure has processed the message

即只有当消息处理函数处理完消息后这个"发送"操作才会返回结束.

2 异步方式(PostMessage)

http://msdn.microsoft.com/en-US/library/9tdesxec(v=vs.80)

BOOL PostMessage(   UINT message,   WPARAM wParam = 0,   LPARAM lParam = 0 );


参数说明与SendMessage一样,不过返回值不同,这个接口的返回是将消息发送到消息队列可立即返回,并不等待消息处理完后返回.

发送消息也可以通过Windos API函数:

LRESULT WINAPI SendMessage(  _In_  HWND hWnd,  _In_  UINT Msg,  _In_  WPARAM wParam,  _In_  LPARAM lParam);

hWnd为要发送的窗口句柄.

LRESULT Res=::SendMessage(HWND hWnd, UINT Msg,  WPARAM wParam, LPARAM lParam);

相对应的异步发送接口为:

BOOL WINAPI PostMessage(  _In_opt_  HWND hWnd,  _In_      UINT Msg,  _In_      WPARAM wParam,  _In_      LPARAM lParam);

使用与::SendMessage一样.


 

原创粉丝点击