Mitja Bezenšek
Mitja Bezenšek

Reputation: 2533

Lost focus issue when using WPF and WindowsInteropHelper

I have a problem with hosting a WPF window inside Excel. What we want to achieve is a window similar to Excel 2013 chart icons next to the chart when chart is selected.

The normal logic is already in place, but there was an issue with click on the ribbon or switching to another window and back to Excel. Both of those scenarios resulted in our window getting hidden.

The solution to this is to set the Owner of our WPF window which is not straight forward when combining Excel and WPF windows. The solution for now was this:

// Getting the active window
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

// Using the WindowInteropHelper to bind WPF window to excel
var wpfWindow = new WPFWindow();
var handle = GetActiveWindow();
helper = new WindowInteropHelper(wpfWindow) { Owner = handle };
wpfWindow.Show();

The above code works fine as long as we only stay in Excel. However the following steps produce a problem:

Any solution to this issue? I have read two similar problems here and here, but they don't offer a working solution.

Upvotes: 0

Views: 493

Answers (1)

d h
d h

Reputation: 101

(I realise this is an old question but hopefully will help someone in the future)

This seems to be a known bug with using window.Show() in wpf windows that hasn't been fixed ( here and here )

Forcing focus to the Owner before Closing seems to work for me (Solution posted in the first link):

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

// Getting the active window
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

// Using the WindowInteropHelper to bind WPF window to excel
var wpfWindow = new WPFWindow();
wpfWindow.Closing += (sender, args) => SetForegroundWindow(new WindowInteropHelper(wpfWindow).Owner);
var handle = GetActiveWindow();
helper = new WindowInteropHelper(wpfWindow) { Owner = handle };
wpfWindow.Show();

Upvotes: 1

Related Questions