Reputation: 863
I'm developing winform app with C#. And I created custom button inherent from UserControl as shown below:
public partial class UserButton : UserControl
{
public UserButton(string UserID)
{
this.Size = new Size(32, 50);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
Img = WaseelaMonitoring.Properties.Resources.T;
g.DrawImage(Img, 0, 0, this.Size.Width, this.Size.Height);
}
}
Note: this is button png image (Click here)
Now, I want to show some buttons on picture box using this code:
UserButton TagButton1 = new UserButton("Button1");
TagButton1.Location = Points[0];
UserButton TagButton2 = new UserButton("Button2");
TagButton2.Location = Points[1];
UserButton TagButton3 = new UserButton("Button3");
TagButton1.Location = Points[2];
Picturebox1.Controls.Add(TagButton1);
Picturebox1.Controls.Add(TagButton2);
Picturebox1.Controls.Add(TagButton2);
Picturebox1.Invalidate();
Okay, when show only one button on the picture box, the background button is transparent(as I want) like this:
But if I want to show two or more buttons beside together the background button is white not transparent like this:
I'm using invalidate picture box and trying invalidate button also, but is not solve that problem.
Upvotes: 1
Views: 220
Reputation: 863
I solved this problem by added this line to initializing constructor:
SetStyle(ControlStyles.Opaque, true);
And overridden this function:
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TRANSPARENT = 0x00000020;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
Upvotes: 0
Reputation: 154995
WinForms does not support true Z-ordering of components; windowed controls (such as Button
and UserControl
) cannot have true alpha-channel support, and the this.Background - Color.Transparent
trick is actually a special-case where the control will re-paint its parent's Background image or color to itself first.
If you are after a more flexible user-experience, I suggest switching to WPF, or doing all of your painting within a single WinForms Control
.
Upvotes: 3