Accelerator Tables Overview
An accelerator table defines keyboard shortcuts (accelerators) that map key combinations to command identifiers used by an application’s menu or command handling code. The operating system delivers accelerator events to a window’s message loop, allowing developers to invoke commands without navigating the menu hierarchy.
Key Concepts
- Accelerator – A structure that describes a key combination (e.g.,
Ctrl+S
) and the command ID it triggers. - Accelerator Table – A collection of
ACCEL
structures loaded from a resource or created at runtime. - Command ID – The identifier used by
WM_COMMAND
messages, typically matching a menu item.
ACCEL Structure
typedef struct tagACCEL {
WORD fVirt; // Flags (FCONTROL, FALT, FSHIFT, FVIRTKEY)
WORD key; // Virtual-key code or ASCII character
WORD cmd; // Command identifier
} ACCEL, *LPACCEL;
Defining an Accelerator Resource
Accelerator tables are usually defined in a resource script (.rc) file:
IDR_MYACCEL ACCELERATORS
BEGIN
"^S", ID_FILE_SAVE, VIRTKEY, CONTROL
"^O", ID_FILE_OPEN, VIRTKEY, CONTROL
"F5", ID_VIEW_REFRESH, VIRTKEY
"A", ID_EDIT_SELECTALL, ASCII, CONTROL
END
Loading an Accelerator Table
Typical usage pattern in a Win32 application:
// Load the accelerator resource
HACCEL hAccel = LoadAcceleratorsW(hInstance, MAKEINTRESOURCEW(IDR_MYACCEL));
if (!hAccel) {
MessageBoxW(nullptr, L"Failed to load accelerators", L"Error", MB_ICONERROR);
}
// In the message loop
while (GetMessageW(&msg, nullptr, 0, 0)) {
if (!TranslateAcceleratorW(hWndMain, hAccel, &msg)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
Runtime Creation
Accelerator tables can also be created dynamically using CreateAcceleratorTable
:
ACCEL accel[2];
accel[0].fVirt = FVIRTKEY | FCONTROL;
accel[0].key = 'C';
accel[0].cmd = ID_EDIT_COPY;
accel[1].fVirt = FVIRTKEY | FALT;
accel[1].key = VK_F12;
accel[1].cmd = ID_DEBUG_TOGGLE;
HACCEL hAccel = CreateAcceleratorTableW(accel, 2);
Common Flags
Flag | Description |
---|---|
FVIRTKEY | Key is a virtual-key code (use VK_ constants). |
FALT | ALT key must be held. |
FCONTROL | CTRL key must be held. |
FSHIFT | SHIFT key must be held. |
ASCII | Key is an ASCII character, not a virtual-key. |
Best Practices
- Keep accelerator keys consistent with standard Windows shortcuts.
- Provide both a menu entry and an accelerator for the same command to improve discoverability.
- Localize accelerator keys carefully; avoid letters that conflict with other language layouts.
- Use
TranslateAccelerator
beforeTranslateMessage
in the message loop.