【发布时间】:2010-11-08 08:49:35
【问题描述】:
我正在尝试在 C# (.NET 3.5 SP1) 中创建一个透明按钮以在我的 WinForms 应用程序中使用。我已经尽一切努力使按钮透明(它应该在按钮下方显示渐变背景),但它就是不工作。
这是我正在使用的代码:
public class ImageButton : ButtonBase, IButtonControl
{
public ImageButton()
{
this.SetStyle(
ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.Transparent, this.ClientRectangle);
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
// rest of class here...
}
问题是按钮似乎从某处获取随机 UI 内存并用 Visual Studio 的 UI 中的一些缓冲区填充自身(在设计模式下)。在运行时,它会抓取一些零缓冲区并且完全是黑色的。
我的最终目标是在不可见的按钮而不是矩形上绘制图像。然而,这个概念应该保持不变。当用户将鼠标悬停在按钮上时,就会绘制一个按钮类型的形状。
有什么想法吗?
编辑:谢谢大家,以下对我有用:
public class ImageButton : Control, IButtonControl
{
public ImageButton()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
SetStyle(ControlStyles.ResizeRedraw, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// don't call the base class
//base.OnPaintBackground(pevent);
}
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TRANSPARENT = 0x20;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
// rest of class here...
}
【问题讨论】:
-
看起来与以下内容重复:stackoverflow.com/questions/201778/…
-
该线程中的建议对我不起作用。
-
尝试使用不透明度值为 0 的新颜色而不是 Color.Transparent 进行绘画