如何向窗口发送消息

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一样.


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值