4
votes

I am writing a WPF control which is hosted in an Word VSTO AddIn (WinForms). Now I have a problem with the mouse click events on a context menu.

If I click on a context menu item on the left half (the part over the WinForms app), the click goes directly to the WinForms app and my context menu does not receive the event.

If I click the right half of the item (part over the WPF form), everything works as expected.

Illustrated the issue

Can someone out there help me solve this issue?

2
Interesting bug! Which version of .NET are you using?Dan Puzey
.Net Framework 4.0 Client ProfileScoregraphic

2 Answers

1
votes

The answer from the inactive blog is:

Declare a class level dispatcher frame object

System.Windows.Threading.DispatcherFrame _frame;

Subscribe to the GotFocusEvent and LostFocusEvent for the menu:

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

Below is the implementation for the event procedures for the GotFocusEvent and 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;
  }
}

In my case, the if statements weren't needed and I subscribed to the events like this

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