简体   繁体   中英

How to make a PictureBox truly transparent

I've got a PictureBox, which can be moved vertically. The image displayed in the PictureBox is a transparent GIF, so when viewed in an image viewer, it has no background.

The problem is that when I move the PictureBox in the application, the PictureBox's background moves around too strangely - almost as if the PictureBox has a background itself.

Before:

在此处输入图片说明

After (while moving):

在此处输入图片说明

Some code:

path = "C:\\note.gif";
note.Image = Image.FromFile(path);
note.Visible = true;
note.BackColor = Color.Transparent;
panel.Controls.Add(note);

I've also tried making the picturebox double buffered, but that doesn't work either.

While WinForms is poorly suited to transparency in usercontrols, it is possible. See this article here. In it the author suggests deriving from Panel rather then UserControl and overridding the OnPaintBackground method to do nothing. this will stop your background from being drawn

protected override void OnPaintBackground(PaintEventArgs pevent)
{
    //do nothing
}

protected override void OnMove(EventArgs e)
{
    RecreateHandle();
}

// Override the CreateParams property:
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle = 0x00000020; //WS_EX_TRANSPARENT
        return cp;
    }
}

Finally, overriding the OnPaint function you can draw your picturebox.

protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;

    //Do your drawing here
}

Using this you could create a custom picturebox with transparency, although note you will get flicker and blurring if you move it around the screen in real-time.

Using this and similar techniques we managed to get a WinForms app, Premex XPort to render with a similar branding to their website. This involved multiple transparent controls, painting hacks and all sorts to get it to display correctly.

In conclusion, the reason why Winforms does this poorly is in Win32 based technologies one control owns one pixel on the screen. There is no way to truly composite pixels with transparency as you would expect in HTML or WPF. Later Windows technologies (WPF) do this particularly well so if you really wish to make heavy use of transparency in your app I would suggest moving to this platform, at least in part (WPF can be hosted within WinForms and vice versa).

Best regards,

Win32 controls are not truly transparent.

Your choices are:

  • Change to WPF
  • Use PictureBox.Region to clip the control's unwanted ("transparent") areas
  • See if there are 3rd party controls which'll do what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM