Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

win32 api edit control and keyboard accelerator

Tags:

c

keyboard

winapi

I am writing a simple notepad editor (customized to suit some extra functionality) in win32 api. The edit control fills up the application area and takes focus at all times. I also need to handle some keyboard commands like Ctl-S. So I use a keyboard accelerator table in the usual way to define the Ctl-S key and in my message loop I have TranslateAccelerator

while (GetMessage(&Msg,NULL,0,0)>0)
   {
   if (!TranslateAccelerator(Msg.hwnd,HAccel,&Msg))
      { TranslateMessage(&Msg); DispatchMessage(&Msg); }
   }

Now my problem is that since the Edit window always has focus, when the user types Ctl-S I dont get a WM_COMMAND message at all. (I understand that the HIWORD of wParam will become 1 for keyboard accelerator, but that's not a problem here).

 case WM_COMMAND:
      switch (LOWORD(wParam))
         {
         ...
         case ID_CTL_S_PRESSED: {My code here} break;
         ...
         }

If I try the code with no Edit control then I do get the WM_COMMAND message above. So how do I go about getting the WM_COMMAND message for a keyboard accelerator when an edit control always has focus?

like image 729
Ambar Chatterjee Avatar asked Nov 26 '13 09:11

Ambar Chatterjee


1 Answers

The first parameter to TranslateAccelerator is documented as:

A handle to the window whose messages are to be translated.

This is misleading and not entirely correct. The section about Processing WM_COMMAND messages (Using Keyboard Accelerators) is more to the point:

When an accelerator is used, the window specified in the TranslateAccelerator function receives a WM_COMMAND or WM_SYSCOMMAND message.

To fix your issue, replace the call to TranslateAccelerator with the following:

if (!TranslateAccelerator(hwndMain,HAccel,&Msg))

Replacing Msg.hwnd with the window handle to your main window will direct the WM_COMMAND message where you want it.

like image 79
IInspectable Avatar answered Oct 16 '22 09:10

IInspectable