Question

Using c# / windows forms. Trying to make a form's background transparent, without it losing its ability to receive clicks.

  1. this.Opacity makes the whole form transparent (not just the background

  2. BackColor = Color.Red;
    TransparencyKey = BackColor;

makes the background of the form transparent and click through-able. I want the form to be transparent , but it should be able to receive clicks

how?

Was it helpful?

Solution

You need to handle WM_NCHITTEST. Note in the snippet below that m.lParam contains packed X and Y coordinates of the mouse position, relative to the top left corner of the screen, and you need to check if the location matches your transparent region.

In this example I'm returning HTCAPTION, which means this region will behave like a caption of the window, i.e. user will be able to drag the window by clicking and dragging this location. See here what other values can be returned and what they mean

protected override void WndProc(ref Message m) {
    switch (m.Msg) {
    case 0x84: // this is WM_NCHITTEST
        base.WndProc(ref m);
        if ((/*m.LParam.ToInt32() >> 16 and m.LParam.ToInt32() & 0xffff fit in your transparen region*/) 
          && m.Result.ToInt32() == 1) {
            m.Result = new IntPtr(2);   // HTCAPTION
        }
        break;
    default:
        base.WndProc(ref m);
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top