开发者

How do I make a form transparent while keeping the controls fully visible?

开发者 https://www.devze.com 2022-12-30 02:20 出处:网络
I would like to have a form in which the controls on the form are fully visible but the form itself is invisible.If I change the form\'s Opac开发者_JAVA百科ity, this makes both the form and the contro

I would like to have a form in which the controls on the form are fully visible but the form itself is invisible. If I change the form's Opac开发者_JAVA百科ity, this makes both the form and the controls on it semi-transparent, so this doesn't work.

I can't do this by setting the form's TransparencyKey, since I have a PictureBox on the form. If the image in the PictureBox happens to contain pixels that match the TransparencyKey, they appear as openings in the form, which I don't want.


TransparencyKey is the only way to get this. Pick the right color. Color.Fuchsia has a long tradition of being the color of choice, going back to the early days of Win32 development. Assault your eye with it to see its merits.


With the caveat that I've never used it, just ran across it once, thought "neat!" and moved on...

Look into System.Drawing.Drawing2D.GraphicsPath and setting the form's Region property. I added two buttons to the basic Windows forms application:

public Form1()
{
    InitializeComponent();

    Rectangle r1 = new Rectangle(button1.Location, button1.Size);
    Rectangle r2 = new Rectangle(button2.Location, button2.Size);

    GraphicsPath gp = new GraphicsPath();
    gp.AddRectangle(r1);
    gp.AddRectangle(r2);

    this.Region = new Region(gp);
}

I've approximated the shape of the button with a rectangle; with this code, you can see the form background color at the buttons' corners. You'll need to work out the enclosing path for each of your controls and add them to the path individually. You'll need to take into account any offset introduced by the form title bar or border style.

Update: I did some investigation and have a couple of possible approaches for the problem:

  • Using the GraphicsPath method, set pictureBox.Visible to False if there is no image loaded.
  • When you load an image into the picture box, analyze the image to get a list of all the colors in it, then randomly generate one that isn't. Set the form's BackColor and TransparencyKey properties to match this new color, Hans Passant's answer.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号