Click-through in C# Form
Asked Answered
O

2

10

I've created a semi-transparent form. I'd like for people to be able to click on the form area, and for form not handle the click. I'd like whatever is underneath the form to receive the click event instead.

Outdoor answered 9/5, 2010 at 16:5 Comment(2)
possible duplicate of Click through transparency for Visual C# Window Forms?Frowsty
What will underneath the form?Inventive
F
20

You can do this with SetWindowLong:

int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);

There are a few magic numbers in here:

  • -20GWL_EXSTYLE

    Retrieves the extended window styles.

  • 0x80000WS_EX_LAYERED

    Creates a layered window.

  • 0x20WS_EX_TRANSPARENT

    Specifies that a window created with this style should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted.

There are numerous articles all over the web on how to do this, such as this one.

Frowsty answered 9/5, 2010 at 16:20 Comment(0)
S
4

The SetWindowLong in @Joey's answer can only make the form semi-transparent after showing the form on screen. If you call SetWindowLong in Form1_Load, the form will be opaque upon creation, and then quickly being changed to semi-transparent. This causes the users to see the non-semi-transparent form for a short moment upon launching the program. To prevent this, you can override CreateParams instead :

public partial class Form1 : Form
{
    protected override CreateParams CreateParams
    {
        get
        {
            const int WS_EX_LAYERED = 0x80000;
            const int WS_EX_TRANSPARENT = 0x20;
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= WS_EX_LAYERED;
            cp.ExStyle |= WS_EX_TRANSPARENT;
            return cp;
        }
    }
}

The code above makes the form semi-transparent before showing the form on screen.

The solution above is similar to this post, which makes the form top-most instead.

Suboxide answered 1/7, 2022 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.