2010-01-25 47 views
-1

我試圖使用HwndSource類在C++/CLI應用程序中加載WPF控件。C++/CLI:互操作窗口配置不正確

UBOOL MyWindowWrapper::Init(const HWND InParentWindowHandle) { 
    Interop::HwndSourceParameters sourceParams("WindowName"); 
    sourceParams.PositionX = 0; 
    sourceParams.PositionY = 0; 
    sourceParams.ParentWindow = (IntPtr)InParentWindowHandle; 
    sourceParams.WindowStyle = (WS_VISIBLE | WS_CHILD); 
    sourceParams.HwndSourceHook = nullptr; 

    InteropWindow = gcnew Interop::HwndSource(sourceParams); 

    Control = gcnew MyWPFUserControl(); 
    InteropWindow->RootVisual = Control; 

    InteropWindow->AddHook(gcnew Interop::HwndSourceHook(
     this, &MyWindowWrapper::MessageHookFunction)); 
    return TRUE; 
} 

而且我定義了一個鉤子函數使鍵盤事件傳遞給窗口:

IntPtr MyWindowWrapper::MessageHookFunction(IntPtr HWnd, int Msg, 
     IntPtr WParam, IntPtr LParam, bool% OutHandled) { 
    IntPtr Result = (IntPtr)0; 
    OutHandled = false; 

    if(Msg == WM_GETDLGCODE) { 
     OutHandled = true; 

     // This tells Windows that we'll need keyboard events for this control 
     Result = IntPtr(DLGC_WANTALLKEYS | DLGC_WANTCHARS | DLGC_WANTMESSAGE); 
    } 
    return Result; 
} 

這裏是我的問題:

  • 的窗口標題是空的(所以不考慮「WindowName」參數)
  • 只傳輸一些鍵盤事件:空格,控件,箭頭都可以,但我不能輸入任何字符在所有的文本框中

我在做什麼錯?

回答

0

關於空標題 - 這是因爲HwndSource窗口的名稱與窗口標題沒有任何關係。代碼在上面創建的HwndSource窗口是由InParentWindowHandle表示的窗口的子項。正是這個窗口的文本用於標題欄。您應該撥打SetWindowText()使用該HWND爲了設置窗口的標題。

至於打字問題,你確定你需要添加一個鉤子嗎?我只創建了一個WPF/Win32集成的小測試應用程序,但我不記得必須做任何特殊的事情來確保WPF控件接收到所有鍵盤輸入。

+0

我實際上做了一些新的空白項目的測試,似乎鍵盤事件傳輸時不需要鉤子。所以它必須來自其他地方......也許它來自WxWidgets。 關於標題,是的,我注意到HwndSource在我的測試項目中作爲Hwnd窗口的孩子附加,而它在主窗口中創建了一個全新的窗口。所以看來,附加一個HwndSource會自動創建一個窗口,就我而言,我不知道爲什麼。 感謝您的回覆 – user258607 2010-01-26 10:26:25

+0

我認爲HwndSource總是會創建一個新窗口 - 這就是它的工作原理。 – Andy 2010-01-26 12:32:09