To add accelerator key functionality to a dialog based program, we first must insert an accelerator resource into the project. In Visual Studio, this can be accomplished by right clicking the top-most folder in the resource view, and selecting the Insert... option. Make sure you give this new resource a unique ID. For this example, I will be using an ID value of IDR_MY_ACCELERATOR
.
Next, we need to add a member variable to our main dialog class. This variable is a handle to the accelerator table, and will be used several places later on. It should look like the following:
HACCEL m_hAccel;
Loading the Table
Now add the following lines of code to the OnInitDialog()
function. As you can see, we initialize our accelerator table handle by calling the LoadAccelerators()
method. Also, note that the text IDR_MY_ACCELERATOR
in the code below should be the ID that you gave to your accelerator resource.
// Load accelerator keys...
m_hAccel = ::LoadAccelerators(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDR_MY_ACCELERATOR));
ASSERT(m_hAccel);
Translating the Accelerator Keys
Now, add the PreTranslateMessage
message to your main dialog class. Then place the following lines of code in the newly created method:
if(m_hAccel)
{
if(::TranslateAccelerator(m_hWnd, m_hAccel, pMsg))
return(TRUE);
}
return CDialog::PreTranslateMessage(pMsg);
All that's left at this point is to add the key mappings to the accelerator resource that we inserted into the project at the beginning. Make sure you give each accelerator key the same ID as the command you want the key to execute.
As an example, let us assume that our program has a “Refresh View” menu item. The corresponding ID value is ID_VIEW_REFRESH
, and we want the [F5] key to mimic this menu command. To do this, we simply add the [F5] key to the accelerator resource and set its ID value to ID_VIEW_REFRESH
, just as it is for the menu item. Now, whenever the [F5] key is pressed, the “Refresh View” menu item will be invoked, just as we want it to be.