如何在WPF中使鼠标事件对窗口不可见?

时间:2011-01-10 13:29:45

标签: c# wpf events mouseevent

我创建了这个类,它可以很好地使我的WPF应用程序对鼠标事件透明。

using System.Runtime.InteropServices;

class Win32

{
    public const int WS_EX_TRANSPARENT = 0x00000020;
    public const int GWL_EXSTYLE = (-20);

    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

    public static void makeTransparent(IntPtr hwnd)
    {
        // Change the extended window style to include WS_EX_TRANSPARENT
        int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        Win32.SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);    
    }

    public static void makeNormal(IntPtr hwnd)
    {
      //how back to normal what is the code ?

    }

}

我运行它来使我的应用程序忽略鼠标事件,但在执行代码后,我希望应用程序恢复正常并再次处理鼠标事件。怎么办?

IntPtr hwnd = new WindowInteropHelper(this).Handle;
Win32.makeTransparent(hwnd);

使应用程序恢复正常的代码是什么?

3 个答案:

答案 0 :(得分:7)

现有类中的以下代码获取现有窗口样式(GetWindowLong),并将WS_EX_TRANSPARENT样式标志添加到现有窗口样式中:

// Change the extended window style to include WS_EX_TRANSPARENT
int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
Win32.SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);

当您想要将其更改回正常行为时,您需要删除您从窗口样式添加的WS_EX_TRANSPARENT标记。您执行此操作这通过执行按位AND NOT操作(与您对 add 标志执行的OR操作相反)。根据{{​​3}}的建议,完全没有必要记住之前检索的扩展样式,因为你要做的就是清除WS_EX_TRANSPARENT标志。

代码看起来像这样:

public static void makeNormal(IntPtr hwnd)
{
    //Remove the WS_EX_TRANSPARENT flag from the extended window style
    int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
    Win32.SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle & ~WS_EX_TRANSPARENT);
}

答案 1 :(得分:1)

此代码获取当前窗口样式:

int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); 

此代码设置WS_EX_TRANSPARENT上的extendedStyle标志:

Win32.SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);

您需要做的就是记住extendedStyle来自GetWindowLong()的{​​{1}},并使用该原始值再次致电SetWindowLong()

答案 2 :(得分:1)

您是否尝试过使用此功能? (这等于窗口)

this.IsHitTestVisible = false;
相关问题