WPF ContextMenu 单击路由到 WinForms 应用程序

标签 wpf winforms ms-word vsto contextmenu

我正在编写一个 WPF 控件,该控件托管在 Word VSTO AddIn (WinForms) 中。现在我遇到了上下文菜单上的鼠标单击事件的问题。

如果我单击左半部分(WinForms 应用程序上方的部分)的上下文菜单项,则单击将直接转到 WinForms 应用程序,并且我的上下文菜单不会收到该事件。

如果我单击该项目的右半部分(WPF 表单上的部分),一切都会按预期工作。

Illustrated the issue

有人可以帮我解决这个问题吗?

最佳答案

非活跃博客的答案是:

声明类级别调度程序框架对象

System.Windows.Threading.DispatcherFrame _frame;

订阅菜单的 GotFocusEvent 和 LostFocusEvent:

_menu.AddHandler(System.Windows.UIElement.GotFocusEvent,new RoutedEventHandler(OnGotFocusEvent));
_menu.AddHandler(System.Windows.UIElement.LostFocusEvent, new RoutedEventHandler(OnLostFocusEvent));

下面是 GotFocusEvent 和 LostFocusEvent 事件过程的实现:

private void OnGotFocusEvent(object sender, RoutedEventArgs e)
{
 if (LogicalTreeHelper.GetParent((DependencyObject)e.OriginalSource) == _menu)
  {
     Dispatcher.BeginInvoke(DispatcherPriority.Normal (DispatcherOperationCallback)delegate(object unused)
        {
         _frame = new DispatcherFrame();
         Dispatcher.PushFrame(_frame);
         return null;
        }, null);
  }
}

private void OnLostFocusEvent(object sender, RoutedEventArgs e)
{
  if (LogicalTreeHelper.GetParent((DependencyObject)e.OriginalSource) == _menu)
  {
     _frame.Continue = false;
  }
}

就我而言,不需要 if 语句,我订阅了这样的事件

<EventSetter Event="GotFocus" Handler="contextMenu_GotFocus" />
<EventSetter Event="LostFocus" Handler="contextMenu_LostFocus" />

关于WPF ContextMenu 单击路由到 WinForms 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11609874/

相关文章:

asp.net - 在网页中嵌入 HTML 或 Word 格式的文本

vba - 删除 Word VBA 中的最后一部分而不覆盖前一个标题

c# - Caliburn Micro WPF 窗口管理

c# - 使用 CanExecute 参数调用 RelayCommand<T>

wpf - 使用 native WPF 控件制作向导的最佳方法是什么

c# - 优雅地关闭系统托盘应用程序

c# - 如何使用C#GDI +图形和Windows窗体递归绘制希尔伯特曲线分形?

.net - WinForms 音量 slider /轨迹栏用户控制

c# - WPF 和 FontAwesome 连字符图标问题

windows - VBA:将多个 Word 文件合并为一个文件后,Microsoft Word 进程不会退出