Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(hwnd, 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?

like image 215
Larsen187 Avatar asked Jan 10 '11 13:01

Larsen187


2 Answers

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);
}
like image 197
Cody Gray Avatar answered Sep 21 '22 00:09

Cody Gray


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.

like image 22
C.Evenhuis Avatar answered Sep 21 '22 00:09

C.Evenhuis