使用WPF和WindowInteropHelper时丢失焦点问题

时间:2014-06-09 12:47:23

标签: c# .net wpf excel

我在Excel中托管WPF窗口时遇到问题。我们想要实现的是一个类似于选择图表时图表旁边的Excel 2013图表图标的窗口。

正常逻辑已经存在,但是单击功能区或切换到另一个窗口并返回到Excel时出现问题。这两种情况都导致我们的窗口被隐藏。

解决方法是在组合Excel和WPF窗口时设置WPF窗口的所有者,这不是直接的。现在的解决方案是:

// 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();

只要我们只停留在Excel中,上面的代码就可以正常工作。但是,以下步骤会产生问题:

  • 从Excel插件显示我们的wpfWindow
  • 切换到当前正在运行的另一个程序(如浏览器,...)
  • 切换回Excel
  • 当我们的表单隐藏时,之前选择的程序将被激活并显示在Excel顶部

此问题的解决方案是什么?我已经阅读了两个类似的问题herehere,但它们没有提供有效的解决方案。

1 个答案:

答案 0 :(得分:1)

(我意识到这是一个古老的问题,但希望将来可以帮助某人)

这似乎是一个已知的错误,在wpf窗口中使用window.Show()尚未修复(herehere

在关闭之前强制关注所有者似乎对我有用(解决方案发布在第一个链接中):

[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();
相关问题