2011-01-10 29 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;