Sunday, February 12, 2012

Solution to Some problems in VC++ MFC in Dialog Based Application


1. 5 Steps for using Accelerators keys for processing keyboard Messages in Dialog Based Application :



Dialogs do not process accelerator tables, but support of them can easily be added. The following describes how to revise your MFC CDialog-derived class to process an accelerator table for a dialog. Code must be added to CDialog::OnInitDialog to load the accelerator table and CDialog::PreTranslateMessage must be overridden to process accelerator keys.
  • If OnInitDialog for the dialog has not yet been overridden, use ClassWizard to add an override for it. Then, after the call to the base class OnInitDialog, add:


              m_hAccel = ::LoadAccelerators(AfxGetResourceHandle(),
                                                               MAKEINTRESOURCE(IDR_ACCELERATOR1);
  • Then, in the dialog's header, add:

                    HACCEL m_hAccel; // accelerator table

  • Then, use ClassWizard to add an override for PreTranslateMessage. Add the following to it:

                 if (WM_KEYFIRST <= pMsg->message && pMsg->message <= WM_KEYLAST)
                    if (m_hAccel && ::TranslateAccelerator
                              (m_hWnd, m_hAccel, pMsg))
                                      return TRUE;
You now have a dialog class that processes accelerator keys.
The next thing to do is to 
  • create an accelerator table resource  (id should be IDR_ACCELERATOR1 or change ID in the step 1 ). In the table specify a key (combination) and a corresponding command id.

  • After creating the accelerator table, use ClassWizard to add a handler for the id(s) you provided in the accelerator table (or Right click on Accelerator table and add handler). Then, you can do most anything in the handler that you need to do when the key is typed.