Transparent or semitransparent panel control

2019-04-13 16:39发布

问题:

Is there any way to make a panel transparent or semi transparent? I haven't found any appropriate property to set transparency for a panel.

I was also trying to make a WPF control with grid (grid background and control background was set to transparent) and place it on normal windows form, but when I put this control on normal Windows Form(not WPF) I don't get the proper transparency.

回答1:

If your display is pretty much static, you can do this to achieve semi-transparency (Source):

class SeeThroughPanel : Panel
{
    public SeeThroughPanel()
    {
    }

    protected override CreateParams CreateParams {
        get {
            var cp = base.CreateParams;
            cp.ExStyle |= 0x00000020;
            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        //base.OnPaint(e);
        e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(50, 0, 0, 0)), this.ClientRectangle);
    }
}

But, this approach is not without problems if you need dynamic rendering on your semi-transparent control. See this question which I have posted. Hope it gets answered someday.



回答2:

Unfortunately, transparency is not natively or well supported in WinForms and is difficult to implement yourself.

If you want a transparent panel that allows you to "see through" the form, take a look at this article, which tells you to set both the Panel's TransparencyKey and BackColor to something like Fuscia. With text/other stuff in the panel this effect may not look so good.

If you want a transparent or translucent panel that shows the form below take a look at this SO question.

I would use WPF all the way, if you are able to use it in a form now.



回答3:

I'm not sure about making the panel semi-transparent, but I know you can use the TransparencyKey property of the form to create completely transparent sections.

For example, set the form's TransparencyKey property to Fuchsia, then set the panel's BackColor to Fuchsia, and it will create a transparent area on the form.

Edit:

Agree with @Callum Rogers about going with WPF. Text directly on the panel shows fringing (see the label in the screenshot). However, if you need to add this quickly to an existing Win Forms app and don't need to show text directly on the panel, it could work for you.