开发者

How can I make a window invisible to mouse events in WPF?

开发者 https://www.devze.com 2023-02-03 05:27 出处:网络
I created this class, and it works perfectly for make my WPF application transparent to mouse events.

I created this class, and it works perfectly for make my WPF application transparent to mouse events.

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(hw开发者_C百科nd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);    
    }

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

    }

}

I run this to make my application ignore mouse events, but after execute the code, I want the application to return to normal and handle mouse events again. How can do that?

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

What is the code to make the application back to normal?


The following code in your existing class gets the existing window styles (GetWindowLong), and adds the WS_EX_TRANSPARENT style flag to those existing window styles:

// 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);

When you want to change it back to the normal behavior, you need to remove the WS_EX_TRANSPARENT flag that you added from the window styles. You do this by performing a bitwise AND NOT operation (in contrast to the OR operation you performed to add the flag). There's absolutely no need to remember the previously retrieved extended style, as suggested by deltreme's answer, since all you want to do is clear the WS_EX_TRANSPARENT flag.

The code would look something like this:

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);
}


This code fetches the current window style:

int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); 

This code sets the WS_EX_TRANSPARENT flag on the extendedStyle:

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

All you need to do is remember what extendedStyle you got from GetWindowLong(), and call SetWindowLong() again with that original value.


Have you tried using this instead? (this equals window)

this.IsHitTestVisible = false;
0

精彩评论

暂无评论...
验证码 换一张
取 消