我想我找到了解決方案,得到了一些線索在這裏:WPF TextBox not accepting Input when in ElementHost in Window Forms
這個問題似乎是與WPF控件到窗體.NET的集成。 按下回車鍵後會發送以下事件: WM_KEYDOWN + WM_CHAR + WM_KEYUP。
忽略輸入WM_CHAR似乎解決了雙重問題,但保持輸入鍵工作。
IntPtr ChildHwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_CHAR)
{
// avoid duplicated enter when parent window is a native window
if (wParam.ToInt32() == 13)
handled = true; //enter is handled by WM_KEYDOWN, and WM_CHAR follows. Removing this WM_CHAR will solve the double enter issue, but keep the enter working
}
if (msg == WM_GETDLGCODE)
{
handled = true;
return new IntPtr(DLGC_WANTALLKEYS | DLGC_WANTARROWS | DLGC_HASSETSEL);
}
return IntPtr.Zero;
}
...
Loaded += delegate
{
HwndSource s = HwndSource.FromVisual(this) as HwndSource;
if (s != null)
s.AddHook(new HwndSourceHook(ChildHwndSourceHook));
};