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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With