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