禁止对话框关闭按钮和Alt+F4

Posted on In Programming

在某些情况下我们需要防止用户单击窗口的标题栏中的关闭按钮关闭 MFC 应用程序。可以删除窗口的WS_SYSMENU 样式, 但是,这样最大化最小化和还原按钮也被删除,并且无法添加。 这是Windows的设计依据。

可以通过禁用关闭按钮来模拟没有关闭按钮的窗口。 在 WM_CREATE 消息处理程序中禁用关闭按钮。使用下面的代码:

CMenu *pSysMenu = GetSystemMenu(FALSE);
ASSERT(pSysMenu != NULL);
VERIFY(pSysMenu->RemoveMenu(SC_CLOSE, MF_BYCOMMAND));

这样删除之后关闭按钮变为灰色,用户无法点击。但是使用Alt+F4仍然可以关闭程序。要将此功能也禁用需要重载CDialog的OnSysCommand方法。代码如下:

void MyDlg::OnSysCommand( UINT nID, LPARAM lParam )
{
    if ( ( nID & 0xFFF0 ) == IDM_ABOUTBOX ) {
        CAboutDlg dlgAbout;   //if you have an about dialog
        dlgAbout.DoModal();
    }
    //add the following code
    else if ( ( nID & 0xFFF0 ) == SC_CLOSE ) {
        //if user clicked the "X"
        OnExit();
        //---end of code you have added
    }
    else {
        CDialog::OnSysCommand( nID, lParam );
    }
}

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *