0

I am trying to implement select all(via ctrl-a) in a CEdit control. I'm doing this by making a class which inherits CEdit and adding a handler for WM_KEYDOWN like this:

void CEditExtended::OnKeyDown( UINT nChar, UINT nRepCnt, UINT nFlags )
{   
  if((nChar == 0x41) && (GetKeyState(VK_CONTROL) & 0x8000) != 0))
    SetSel(0, -1);

  CEdit::OnKeyDown(nChar, nRepCnt, nFlags);
}

Looking around on the web, this should work, but it never registers both ctrl and a at the same time, either one or the other.

Logick
  • 301
  • 1
  • 6
  • 14

3 Answers3

3

Try this code:

void CEditExtended::PreTranslateMessage(MSG* pMsg)
{
 if(pMsg->message == WM_KEYUP )
    {
        if ( (LOWORD(pMsg->wParam) & VK_CONTROL) == VK_CONTROL )
        {

         /// blah

        }
    }

    return CEdit::PreTranslateMessage(pMsg);
}
QuangNHb
  • 304
  • 2
  • 9
  • Why is this code checking `LOWORD(wParam)` for `VK_CONTROL` and ignoring `VK_A`? This code is not ensuring that the user is actually pressing `CTRL-A`, but is simply reacting when `CTRL` itself is being released. I would think it needs to be like this instead: `if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == 'A') && (GetKeyState(VK_CONTROL) < 0)) { ... return TRUE; } else return CEdit::PreTranslateMessage(pMsg);` – Remy Lebeau Sep 03 '15 at 00:27
2

To implement Ctrl+A for all edit controls in a window, override CWnd::PreTranslateMessage to check for the key sequence and whether focus is on an edit control. If so, select its text.

BOOL CMyWindow::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'A' && GetKeyState(VK_CONTROL) < 0) {
        if (auto edit = dynamic_cast<CEdit*>(GetFocus())) {
            edit->SetSel(0, -1, FALSE);
            return TRUE;
        }
    }
    return __super::PreTranslateMessage(pMsg);
}
Edward Brey
  • 40,302
  • 20
  • 199
  • 253
0

Another way to implement CTRL+A without extending CEdit class.

Override PreTranslateMessage() member function of the dialog that has a edit control.

BOOL CMyDialog::PreTranslateMessage(MSG* pMsg)
{
    if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == 'A')
       && GetKeyState(VK_CONTROL) < 0)
    {
        CWnd *pWnd = GetFocus();
        if (pWnd != NULL)
        {
            CString className;

            GetClassName(pWnd->GetSafeHwnd(), className.GetBuffer(80), 80);
            className.ReleaseBuffer();
            if (className.CompareNoCase(_T("edit")) == 0)
            {
                pWnd->SendMessage(EM_SETSEL, 0, -1);
                return TRUE;
            }
        }
    }

    return CDialogEx::PreTranslateMessage(pMsg);
}
Hill
  • 3,391
  • 3
  • 24
  • 28