65.9K
CodeProject 正在变化。 阅读更多。
Home

加速键和 WTL 对话框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.29/5 (10投票s)

2006 年 3 月 23 日

viewsIcon

45525

downloadIcon

1017

一篇关于在 WTL 对话框中使用加速器的文章。

image

引言

我在 CodeProject 上搜索了很久,但没有找到关于在 WTL 对话框中使用加速器的示例。我曾在 MFC 对话框中广泛使用过加速器,但无法弄清楚如何将此功能添加到 WTL 对话框中。 就像很多事情一样,一旦你弄清楚了,它就变得非常容易了。 好吧,开始吧....

使用代码

声明一个加速器的句柄,并添加 CMessageFilter(如果尚未添加)。

#pragma once

class CMainDlg : public CDialogImpl<CMainDlg>, 
         public CUpdateUI<CMainDlg>,
         public CMessageFilter, 
         public CIdleHandler
{
private:
    HACCEL    m_haccelerator;
//.......

};

然后在你的 OnInitDialog 中,将 m_haccelerator 变量赋值给加速器资源,在本例中为 IDR_MAINFRAME

LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, 
        LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
    // .......


    //Bind keys...

    m_haccelerator = AtlLoadAccelerators(IDR_MAINFRAME);

    // register object for message filtering and idle updates    

    CMessageLoop* pLoop = _Module.GetMessageLoop();
    ATLASSERT(pLoop != NULL);
    pLoop->AddMessageFilter(this);
    pLoop->AddIdleHandler(this);

    //...............


    return TRUE;
}

然后我们需要重载 PreTranslateMessage 函数...

BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{    
    if(m_haccelerator != NULL)
    {
        if(::TranslateAccelerator(m_hWnd, m_haccelerator, pMsg))
            return TRUE;
    }

    return CWindow::IsDialogMessage(pMsg);
}

另外,在你的构造函数中,初始化加速器的句柄。

CMainDlg::CMainDlg()
{
    //..................


    m_haccelerator = NULL;

    //..................

}

如果对话框不是模态的,则需要将其设置为模态,才能使 PreTranslateMessage 起作用。 这很容易通过...

int WINAPI _tWinMain(HINSTANCE hInstance, 
    HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
    _Module.Init(NULL, hInstance);

    CMessageLoop myMessageLoop;
    _Module.AddMessageLoop(&myMessageLoop);

    CMainDlg dlgMain;
    dlgMain.Create(NULL);
    dlgMain.ShowWindow(nCmdShow);

    int retValue = myMessageLoop.Run();

    _Module.RemoveMessageLoop();
    _Module.Term();

    return retValue;
}

并且确保包含 atlmisc.h

© . All rights reserved.