How can I pass WM_KEYDOWN messages to the WinForms control inside CWinFormsView?

StackOverflow https://stackoverflow.com/questions/6031876

  •  14-11-2019
  •  | 
  •  

Frage

I have a WinForms control (let's say C) inside the CWinFormsView V of an MDI application. C overrides the OnKeyDown method. I have overriden also OnMouseUp in C and I call the Focus() method there, so when I click inside C the keyboard messages go directly to it and everything works correctly.

However, I'd like to be able to control C using the keyboard when I switch to V without the need to click inside the view. How can I achieve that? Do I need to catch WM_KEYDOWN messages in V and pass them manually to the hosted control (in other words, C)? C is actually a child window of V, shouldn't it somehow work automatically?

War es hilfreich?

Lösung 2

I actually solved the problem with the following code in the V view:

BOOL CMyView::PreTranslateMessage(MSG* pMsg)
{
    if( pMsg->message == WM_KEYDOWN || pMsg->message == WM_MOUSEWHEEL )
    {
        ::SendMessage( (HWND) m_myControl->Handle.ToInt32(), pMsg->message, pMsg->wParam, pMsg->lParam );
    }

    return CWinFormsView::PreTranslateMessage(pMsg);
}

Also I removed the code that sets focus to C on mouse click. This way it is never focused but receives the parent view's messages (I need WM_KEYDOWN and WM_MOUSEWHEEL) from PreTranslateMessage. Not settings the focus is important because otherwise I would lose the ability to switch between MDI views using Ctrl+Tab (if C was focused). So now I can switch between them freely, then when V becomes active I can use the keys to control C but I still can use Ctrl+Tab to switch to another view without having to use the mouse.

Andere Tipps

If I followed your question, the easiest way is to have V forward the presses to C.

Look at Form.KeyPreview - for V - which will let V see all the key presses when it or one of it's children have focus. You can then forward it to C.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top