Excel 2007, WPF: Events are not fired for items that overlap Excel UI for WPF context Menus


Symptoms:

Consider a scenario where you have a VSTO 3.0 add-in for Excel 2007 that loads up a WPF control in a custom task pane as a context menu.

You have also subscribed to the MenuClick event for each item of the Context Menu. The context menu is displayed but some of the items of menu are displayed over the Excel sheet area as displayed in the below picture :-

Excel

If you click on the item which overlaps the Excel UI, you will notice that the menu click event is not fired for those items. The issue does not reproduce with Windows Form controls.

Cause:

This issue is a known issue reported with WPF.

 

Resolution:

One of the workarounds is to use the DispatcherFrame to pump messages and subscribe to GotFocusEvent and LostFocusEvent for the menu. (Similar to DoEvents method is VB6)

  1. Declare a class level dispatcher frame object 
    System.Windows.Threading.DispatcherFrame _frame;
  2. 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;
      }
    }
Comments (1)

  1. Erwin says:

    I encountered the same issue in an Outlook 2007 Addin. However, the solution prevents the Outlook.exe process from terminating when Outlook is closed. Any ideas?

Skip to main content