如何向窗口发送消息

来源:岁月联盟 编辑:exp 时间:2012-08-31

CWnd类的SendMessage和PostMessage成员函数.
第一步:在头文件中自定义消息,如:
[cpp]
#define WM_USER_MSG (WM_USER +100) 
第二步:通过类向导点击Message选项卡,添加自定义消息WM_USER_MSG.
第三步:实现自定义消息的响应函数.
第四步:发送消息.
发送消息有两种方式.
1 同步发送(SendMessage)
[plain]
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)
[cpp]
// 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解说如下:
[plain]
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)
[plain] view plaincopy
BOOL PostMessage( 
   UINT message, 
   WPARAM wParam = 0, 
   LPARAM lParam = 0  
); 

参数说明与SendMessage一样,不过返回值不同,这个接口的返回是将消息发送到消息队列可立即返回,并不等待消息处理完后返回.
发送消息也可以通过Windos API函数:
[cpp]
LRESULT WINAPI SendMessage( 
  _In_  HWND hWnd, 
  _In_  UINT Msg, 
  _In_  WPARAM wParam, 
  _In_  LPARAM lParam 
); 
hWnd为要发送的窗口句柄.
[cpp]
LRESULT Res=::SendMessage(HWND hWnd, UINT Msg,  WPARAM wParam, LPARAM lParam); 
相对应的异步发送接口为:
[cpp]
BOOL WINAPI PostMessage( 
  _In_opt_  HWND hWnd, 
  _In_      UINT Msg, 
  _In_      WPARAM wParam, 
  _In_      LPARAM lParam 
); 
使用与::SendMessage一样.