Method 1:
Shortcut for Main Menu
Bool cexampledlg: pretranslatemessage (MSG * PMSG)
{
// Todo: Add dedicated code and/or call the base class here
If (PMSG-> message = wm_keydown)
{
Switch (PMSG-> wparam)
{
Case 'F ':
If (: getkeystate (vk_menu) <0)
MessageBox ("hello ");
}
}
Return cdialog: pretranslatemessage (PMSG );
}
The above Code uses Alt + F to respond to the "file" main menu item. The captain of the main menu is set to "file (& F )"
Non-main menu shortcut
1. Insert a new accelerator to the resource and associate the acceleration key with the corresponding response control (such as a button ).
2. declare in the header file of the dialog box:
Haccel m_haccel;
3. initialize m_haccel In the constructor of the dialog box.
M_haccel =: loadaccelerators (AfxGetInstanceHandle (), makeintresource (idr_accelerator1 ));
4. Reload the pretranslatemessage function in the dialog box.
Bool caboutdlg: pretranslatemessage (MSG * PMSG)
{
If (m_haccel)
{
If (: translateaccelerator (m_hwnd, m_haccel, PMSG ))
{
Return (true );
}
}
Return cdialog: pretranslatemessage (PMSG );
}
Method 2
1. Declare the prototype of the hotkey Message Processing Function
In. H, add the following statement to the Message ing Declaration (after afx_msg:
Lresult onhotkey (wparam, lparam );
2. The message is associated with the corresponding processing function.
Add a message ing macro to. cpp to associate the message with the corresponding processing function,
On_message (wm_hotkey, onhotkey );
3. To facilitate future operations
Create a function in the class to respond to the wm_create and wm_destroy messages in advance.
Framework of oncreate () and ondestroy ()
4. register the hotkey with the System
Add the following code to the oncreate () function to register the hotkey with the system. In this example, the hotkey is set
CTRL + Shift +.
Registerhotkey (m_hwnd, 1001, mod_control | mod_shift, 'A ');
Registerhotkey (m_hwnd, 1002, mod_control | mod_shift, 'A ');
5. Handling hotkeys
Process the hotkey in the message processing function onhotkey () and add the program code you want to run.
Lresult C ***: onhotkey (wparam, lparam)
If (wparam = 1001 | wparam = 1002)
Cwnd: setforegroundwindow (); // make the activated window appear in the foreground
MessageBox ("Hello! ";
// You can add code here
Return 0;
6. Remove the hotkey after running the program.
In ondestroy (), unregisterhotkey () is used to cancel hotkey registration and release system resources.
Unregisterhotkey (m_hwnd, 1001 );
Unregisterhotkey (m_hwnd, 1002 );