我最近开始探索 Visual Studio。
我试图创建一个幻灯片菜单。更具体地说,当用户按下按钮时,会在右侧弹出一个子菜单。为此,我放置了一个 Panel
来自行调整大小。除了功能之外,我还想添加更多设计并使 Panel
看起来有点褪色。
我知道 Visual Studio 中的 Panels
没有不透明度,但我在想是否有人知道如何实现它。我尝试了 Picture Box
,但它也没有将 Opacity 作为属性。我避免使用 visual studio 提供的常规 Menu
对象,因为我想添加更多设计。有什么想法吗?
最佳答案
- 创建一个继承自
Panel
的类. - 设置
ControlStyle.Opaque
使用SetStyle
在构造函数中进行控制.
If true, the control is drawn opaque and the background is not painted.
- 覆盖
CreateParams
并设置WS_EX_TRANSPARENT
风格。
Specifies that a window created with this style is to be transparent. That is, any windows that are beneath the window are not obscured by the window. A window created with this style receives WM_PAINT messages only after all sibling windows beneath it have been updated.
- 创建一个
Opacity
属性,接受 0 到 100 之间的值,将用作背景的 alpha channel 。 - 覆盖
OnPaint
并使用从BackGroundColor
和Opacity
创建的启用 alpha 的Brush
填充背景。
完整代码
public class ExtendedPanel : Panel
{
private const int WS_EX_TRANSPARENT = 0x20;
public ExtendedPanel()
{
SetStyle(ControlStyles.Opaque, true);
}
private int opacity = 50;
[DefaultValue(50)]
public int Opacity
{
get
{
return this.opacity;
}
set
{
if (value < 0 || value > 100)
throw new ArgumentException("value must be between 0 and 100");
this.opacity = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (var brush = new SolidBrush(Color.FromArgb(this.opacity * 255 / 100, this.BackColor)))
{
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
base.OnPaint(e);
}
}
截图
关于c# - 在 Visual Studio 窗口窗体中的面板上使用不透明度有什么技巧吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400320/