WM_KEYDOWN - capturing keypress causing event [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-04 19:29:55

There are several ways to solve this problem. None of which will give you "nano-second" accuracy but here they are.

If you want the keypress to be recieved by an active window or dialog you handle a WM_KEYDOWN even in the WINPROC of the dialog/window like so.

void InSomePlace()
{
  WNDCLASS wndClass
  ZeroMemory( &wndClass, sizeof(wndClass) );

  // Initialize wndClass members here
  wndClass.lpszClassName = _T("MyWindow");
  wndClass.lpfnWndProc = &MyWndProcHandler; // 

  RegisterClass( &wndClass );
  HWND hWnd = CreateWindow( _T("MyWindow", /* lots of other parameters */ );

  MSG msg;
  BOOL bRet;
  while ( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0 )
  {
    if (bRet == -1)
    {
      // handle the error and possibly exit
    }
    else
    {
      TranslateMessage(&msg); 
      DispatchMessage(&msg); 
    }
  }
}

LRESULT CALLBACK MyWndProcHandler( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
  switch ( uMsg )
  {
    // Lots of case statements, in particular you want a WM_KEYDOWN case
    case WM_KEYDOWN:
      if ( wParam == 'S' )
      {
        // Do something here
        return 0L;
      }
      break;
  }

  return DefWindowProc( hwnd, uMsg, wParam, lParam );
}

For a DialogBox its very similar, you would still have a DLGPROC which is passed as the last parameter to DialogBox/CreateDialog

void InSomePlace( HINSTANCE hInstance, HWND hParentWindow )
{
  DialogBox( hInstance, _T("MyDialogTemplate"), hParentWindow, &MyDialogProc );
}

INT_PTR CALLBACK MyDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
  case ( uMsg )
  {
    // Lots of case statements, in particular you want a WM_KEYDOWN case
    case WM_KEYDOWN:
      if ( wParam == 'S' )
      {
        // Do something here
        SetWindowLong(hwndDlg, DWL_MSGRESULT, 0L);
        return TRUE;
      }
      break;
  }
  return FALSE;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!