C# WinForm:如何使用正确的背景颜色实现按钮
我正在用C#开发winform应用程序。我从UserControl中创建了自定义按钮,如下所示:C# WinForm:如何使用正确的背景颜色实现按钮,c#,winforms,C#,Winforms,我正在用C#开发winform应用程序。我从UserControl中创建了自定义按钮,如下所示: public partial class UserButton : UserControl { public UserButton(string UserID) { this.Size = new Size(32, 50); this.BackColor = Color.Transparent; } protected overrid
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);
}
}
注意:这是按钮png图像()
现在,我想用以下代码在图片框上显示一些按钮:
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();
好的,当图片框上只显示一个按钮时,背景按钮是透明的(如我所愿),如下所示:
但是如果我想同时显示两个或多个按钮,背景按钮是白色的,不透明,如下所示:
我正在使用invalidate picture box并尝试使用invalidate按钮,但这并不能解决该问题。WinForms不支持组件的真正Z顺序;窗口控件(如
按钮
和用户控件
)不能具有真正的alpha通道支持,而this.Background-Color.Transparent
技巧实际上是一种特殊情况,控件将首先重新绘制其父控件的背景图像或颜色
如果您想要更灵活的用户体验,我建议切换到WPF,或者在单个WinForms
控件中完成所有绘制工作
我通过在初始化构造函数中添加以下行解决了此问题:
SetStyle(ControlStyles.Opaque, true);
并重写此函数:
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TRANSPARENT = 0x00000020;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
对用户控件使用TransparencyKey如何?类似于:TransparencyKey=Color.White(从用户控件本身内部)