2011-01-10 60 views
5

我创建了这个类,它完美地适用于让我的WPF应用程序对鼠标事件透明。如何使窗口对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); 

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

回答

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操作来完成此操作(与执行添加标志的OR操作相反)。根据deltreme's answer的建议,绝对不需要记住先前检索到的扩展样式,因为您只需清除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

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

int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); 

这个代码设定WS_EX_TRANSPARENT标志上extendedStyle

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

所有你需要做的是记住extendedStyleGetWindowLong()了,并用该原始值再次呼叫SetWindowLong()

+0

很抱歉,但不明白,可以SHOWME普莱舍如何。 – Larsen187 2011-01-10 13:49:37

+2

没有理由记住`extendedStyle`。您只需检索当前值并从中删除`WS_EX_TRANSPARENT`标志。看到我的[回复](http://stackoverflow.com/questions/4647345/how-can-i-make-a-window-invisible-to-mouse-events-in-wpf/4647540#4647540)了解更多详情。 – 2011-01-10 13:59:10

+0

@Cody Gray:同意,这是一个更优雅的解决方案。 – 2011-01-10 14:25:26

1

你试过用这个吗? (这等于窗口)

this.IsHitTestVisible = false;