I have created a Windows GUI program using C and the Windows API, and I want the program to utilise keyboard accelerators. I have set up some 开发者_运维问答accelerators, which are working correctly, but when focus goes to a child Window of my program's main window, such as a list view control or a status bar control, it appears that the keyboard accelerators are being translated to WM_COMMAND messages for the child windows rather than the main window. Because of this, my handling of the appropriate WM_COMMAND messages in the main window's WndProc is ignored when the focus is on a child control.
How should I resolve this problem?
I found the answer. The child windows of the main window must be subclassed so that the WM_COMMAND messages generated by the keyboard accelerators can be intercepted and passed to the parent window.
This involves changing the window procedure of the control to a different one. The alternate procedure handles the messages that should be intercepted by sending them to the parent window. A pointer to the original window procedure must also be stored somewhere so that the control can function correctly.
The window procedure can be altered using SetWindowLongPtr with GWLP_WNDPROC.
Here is a simple example of how to do this by storing a pointer to the original window procedure in the control's user data value (GWLP_USERDATA):
The code to change the window procedure and store the original procedure in GWLP_USERDATA:
SetWindowLongPtr( hWnd, GWLP_USERDATA, ( LONG_PTR )SetWindowLongPtr( hWnd, GWLP_WNDPROC, ( LONG_PTR )WndProc ) );
The intercepting window procedure:
static LRESULT CALLBACK WndProc( const HWND hWnd, const UINT message, const WPARAM wParam, const LPARAM lParam )
{
switch( message )
{
case WM_COMMAND:
SendMessage( GetParent( hWnd ), message, wParam, lParam );
return 0;
default:
//Assume that GWLP_USERDATA has been set to the original window procedure.
return CallWindowProc( ( WNDPROC )GetWindowLongPtr( hWnd, GWLP_USERDATA ), hWnd, message, wParam, lParam );
}
}
Another way is avoid using TranslateAccelerator for child window, sample code:
if (mainWidget() && msg.hwnd == mainWidget()->hwnd()) {
if (TranslateAccelerator(msg.hwnd, hMainAccelTable, &msg)) {
continue;
}
}
TranslateMessage(&msg);
DispatchMessage(&msg);
if the message is not the mainWidget's, we do not translateaccelerator for it using the accelerator table of the main widget.
精彩评论