非模态对话框失去焦点后销毁对话框

非模态对话框失去焦点后销毁对话框?

这里响应ON_WM_ACTIVATE()事件,

对应的消息处理函数为:afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);

nState有三种状态:

  • WA_INACTIVE   The window is being deactivated.

  • WA_ACTIVE   The window is being activated through some method other than a mouse click (for example, by use of the keyboard interface to select the window).

  • WA_CLICKACTIVE   The window is being activated by a mouse click.
    当窗口得到或失去焦点时,会触发这个消息.
    我们接收到这个消息后,可以判断到底是哪一种状态.
    失去焦点当然就得处理WA_INACTIVE消息,然后销毁掉窗口,代码如下:
    void CXXXDlg::OnActivate( UINT nState, CWnd* pWndOther, BOOL bMinimized ) { CDialog::OnActivate(nState, pWndOther, bMinimized); if (WA_INACTIVE == nState) { PostMessage(WM_CLOSE, NULL, NULL); } }

  • 这个函数之后会调用OnCancel消息去处理其它消息.

  • 所有源代码如下:(注意,我在对话框模板资源里面添加了一个Slider Control)
     #pragma once // CSliderCtrlDlg dialog class CSliderCtrlDlg : public CDialog { DECLARE_DYNAMIC(CSliderCtrlDlg) public: CSliderCtrlDlg(CWnd* pParent = NULL); // standard constructor virtual ~CSliderCtrlDlg(); virtual void PostNcDestroy(); int m_pos; // 这个变量用于保存dialog上面的数据. // Dialog Data enum { IDD = IDD_DIALOG_SPLITER }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized); afx_msg void OnCancel(); }; ////////////////////////////////////CPP // SliderCtrlDlg.cpp : implementation file // #include "stdafx.h" #include "SliderClr.h" #include "SliderCtrlDlg.h" // CSliderCtrlDlg dialog IMPLEMENT_DYNAMIC(CSliderCtrlDlg, CDialog) BEGIN_MESSAGE_MAP(CSliderCtrlDlg, CDialog) ON_WM_ACTIVATE() ON_COMMAND(IDCANCEL, (AFX_PMSG)&CSliderCtrlDlg::OnCancel) END_MESSAGE_MAP() CSliderCtrlDlg::CSliderCtrlDlg(CWnd* pParent /*=NULL*/) : CDialog(CSliderCtrlDlg::IDD, pParent) { m_pos = 0; } CSliderCtrlDlg::~CSliderCtrlDlg() { } void CSliderCtrlDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Slider(pDX, IDC_SLIDER1, m_pos); } void CSliderCtrlDlg::OnCancel() { UpdateData(TRUE); wchar_t buf[4] = {0}; MessageBox(_itow(m_pos, buf, 10)); DestroyWindow(); } void CSliderCtrlDlg::OnActivate( UINT nState, CWnd* pWndOther, BOOL bMinimized ) { CDialog::OnActivate(nState, pWndOther, bMinimized); if (WA_INACTIVE == nState) { PostMessage(WM_CLOSE, NULL, NULL); } } void CSliderCtrlDlg::PostNcDestroy() { CDialog::PostNcDestroy(); delete this; }

  • 调用: CSliderCtrlDlg* pSliderCtrlDlg = new CSliderCtrlDlg; pSliderCtrlDlg->Create(IDD_DIALOG_SPLITER, this); pSliderCtrlDlg->ShowWindow(SW_SHOW);

  • 你可能感兴趣的:(非模态对话框失去焦点后销毁对话框)