Transparent User Control in .net

余生长醉 提交于 2019-12-24 18:33:15

问题


I'm trying to make a web style button with user control. I need to make User Control's background transparent. How to do this without making controls invisible. Also I'll need transparent Label and PictureBox.

Trying to make something like this:

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent;

回答1:


All three controls you list already have the ControlStyles.SupportsTransparentBackColor style turned on. Just set the BackColor property in the designer, Web tab. It is very unclear why that's not good enough for you.

It is otherwise an illusion, Windows Forms implements it by asking the Parent control to draw itself in the OnPaintBackground() method so it provides the background pixels. One notable thing that doesn't work is overlapping controls. You only see the Parent pixels, not the pixels of the overlapped control. That's fixable but the code is fugly.

The only other transparency option is Form.TransparencyKey. That's true transparency, implemented by using overlays in the video adapter. Problem is that this only works on toplevel windows. Forms, not controls.

These restrictions are inherent in the Windows Forms rendering model, using individual windows for the controls. A web browser doesn't have that same restriction, it emulates controls by drawing them. Layers of paint, that makes transparency trivial by just not painting. WPF uses that rendering model as well.




回答2:


If you mean you want "partial transparency", see this for nice solution: Opacity of Buttons/TextBoxes - VB.NET

(setting the background color using Alpha value)

I know the above sample is VB but it applies to C# as well. :)




回答3:


You can use this code : ImageButton() is my constructor.

  public ImageButton()
    {
      InitializeComponent();

      this.SetStyle(ControlStyles.Opaque, true);
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
    }

    protected override CreateParams CreateParams
    {
      get
      {
          CreateParams parms = base.CreateParams;
          parms.ExStyle |= 0x20;  
          return parms;
      }
    }


来源:https://stackoverflow.com/questions/4117356/transparent-user-control-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!