效果如图所示
这是失去焦点后找不到窗口,并且无法与主窗体交互的情况
这是修复后可以正常交互的情况
解决方法是设置Owner
属性
关键代码
//GetForegroundWindow API
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
//从Handle中获取Window对象
static Window GetWindowFromHwnd(IntPtr hwnd)
{
var window = HwndSource.FromHwnd((IntPtr)hwnd);
dynamic customWindow = window.RootVisual;
return customWindow;
}
//调用GetForegroundWindow然后调用GetWindowFromHwnd
static Window GetTopWindow()
{
var hwnd = GetForegroundWindow();
if (hwnd == null)
return null;
return GetWindowFromHwnd(hwnd);
}
public NotShowInTaskbarWindow(bool isSetOwner,Window window=null)
{
InitializeComponent();
if (isSetOwner)
{
if (window != null)
{
Owner = window;
}
else
{
Owner = GetTopWindow();
//如果有传参UserControl作为内容,可以尝试使用Window.GetWindow(DependencyObject) 方法
}
}
}
示例代码
参考资料
WPF中Window的ShowInTaskbar、Owner和Topmost属性
Get WPF window by hWnd
Window.GetWindow(DependencyObject) 方法