一般情況下,激活父窗口的時候,子窗口會失去焦點,同理,激活子窗口的時候,父窗口也會失去焦點,這在某些時候不太好看,比如子窗口作為ToolWindow漂浮在父窗口上面時。Visual Studio好像也有這個問題,當激活其中某個處於浮動狀態的DockingPanel時,Visual Studio主窗口會失去焦點。
上兩幅圖,更明白點,
一般效果如下:
我們現在追求的效果如下:
恩,這裡有個簡單的包裝,呵呵,復制下代碼就可以直接使用了(Framework版本需要3.5):
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace YourNamespace
{
public static class WindowActiveService
{
internal class WindowActiveHelper
{
[DllImport("user32", CharSet = CharSet.Auto)]
private extern static int SendMessage(
IntPtr handle, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
// ReSharper disable InconsistentNaming
private const int WM_NCACTIVATE = 0x086;
// ReSharper restore InconsistentNaming
private IntPtr ownerHwnd = IntPtr.Zero;
private IntPtr childHwnd = IntPtr.Zero;
private HwndSource ownerHwndSource;
private HwndSource childHwndSource;
private HwndSourceHook ownerHook;
private HwndSourceHook childHook;
private bool childActive;
private bool ownerActive;
private static IntPtr GetWindowHwnd(Window window)
{
var helper = new WindowInteropHelper(window);
return helper.Handle;
}
private IntPtr FilterChildMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr