让 APP 发送和处理自定义消息
1,自定消息;由于 app 不是继承与窗口类,所以不能向窗口那样 send 或 post message;
2,可以直接在 app 中 post thread message,例如这里的 WM_APP1;也可以从窗口中 post WM_COMMAND,例如这里的 WM_APP2;
2,防止 thread message 丢失,下面这个例子中,WM_APP2在主窗口创建后被post,处理函数弹出一个dialog,这时如果不显示滴用PeekMessage,thread message就被发到了窗口线程里,就丢失了。参考:
#define WM_APP1 (WM_APP+1) #define WM_APP2 (WM_APP+2)
BEGIN_MESSAGE_MAP(CProgramApp, CWinApp) (WM_APP1, &CProgramApp::OnHandleApp1) (WM_APP2, &CProgramApp::OnHandleApp2) ON_COMMAND(ID_APP_ABOUT, &CProgramApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) END_MESSAGE_MAP()
BOOL CProgramApp::InitInstance() { ... // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); // // WM_APP2 was posted after main window created, need dispatch all those msg, // then post the thread msg, otherwise, the thread message lost. // MSG Msg; while(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } this->PostThreadMessage(WM_APP1, 0, 0); return TRUE; } void CProgramApp::OnHandleApp1(WPARAM wParam, LPARAM lParam) { AfxMessageBox(_T("WM_APP1 handler")); } void CProgramApp::OnHandleApp2() { AfxMessageBox(_T("WM_APP2 handler")); }
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndStatusBar.Create(this)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // this->PostMessage(WM_COMMAND, WM_APP2, 0); return 0; }
-