Creating a Hot-Key Control

The following function creates a hot-key control, uses the HKM_SETRULES and HKM_SETHOTKEY messages to initialize it, and returns a handle to the control. This hot-key control does not allow the user to choose a hot key that is a single unmodified key, nor does it permit the user to choose only SHIFT and a key. (These rules effectively prevent the user from choosing a hot key that might be accidentally entered while typing text.)

// InitializeHotkey - creates a hot-key control and sets rules

// and default settings for it.

// Returns the handle of the hot-key control.

// hwndDlg - handle of the parent window (dialog box)

//

// Global variable

// g_hinst - handle of the application instance

extern HINSTANCE g_hinst;

HWND WINAPI InitializeHotkey(HWND hwndDlg)

{

// Ensure that the common control DLL is loaded.

InitCommonControls();

hwndHot = CreateWindowEx(

0, // no extended styles

HOTKEY_CLASS, // class name

"", // no title (caption)

WS_CHILD | WS_VISIBLE, // style

10, 10, // position

200, 20, // size

hwndDlg, // parent window

NULL, // uses class menu

g_hinst, // instance

NULL // no WM_CREATE parameter

);

SetFocus(hwndHot);

// Set rules for invalid key combinations. If the user

// does not supply a modifier key, use ALT as a modifier.

// If the user supplies SHIFT as a modifier key, use

// SHIFT + ALT instead.

SendMessage(hwndHot, HKM_SETRULES,

(WPARAM) HKCOMB_NONE | HKCOMB_S, // invalid key combinations

MAKELPARAM(HOTKEYF_ALT, 0)); // add ALT to invalid entries

// Set CTRL + ALT + A as the default hot key for this window.

// 0x41 is the virtual-key code for 'A'.

SendMessage(hwndHot, HKM_SETHOTKEY,

MAKEWORD(0x41, HOTKEYF_CONTROL | HOTKEYF_ALT), 0);

return hwndHot;

}