WPF 窗口穿透

不太懂, 先记着, 大概是调用 user32.dll 里的函数, 参数看不懂

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    private const uint WS_EX_LAYERED = 0x80000;
    private const int WS_EX_TRANSPARENT = 0x20;
    private const int GWL_EXSTYLE = (-20);

    [DllImport("user32", EntryPoint = "SetWindowLong")]
    private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);

    [DllImport("user32", EntryPoint = "GetWindowLong")]
    private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);

    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

    /// <summary>
    /// 通过标题找到窗口并设置其是否穿透
    /// </summary>
    /// <param name="title">窗口标题</param>
    /// <param name="flag">是否穿透, 默认值true</param>
    public static void SetWindowPenetrate(string title, bool flag = true)
    {
        IntPtr hwnd = FindWindow(null, title);
        uint style = GetWindowLong(hwnd, GWL_EXSTYLE);
        if (flag)
            SetWindowLong(hwnd, GWL_EXSTYLE, style | WS_EX_TRANSPARENT | WS_EX_LAYERED);
        else
            SetWindowLong(hwnd, GWL_EXSTYLE, style & ~(WS_EX_TRANSPARENT | WS_EX_LAYERED));
    }

SetWindowLong 的第一个参数是窗口的句柄, 如果是自己的Form或者Window, 把他写在类里, 直接用this.Handle就行了