c# - 在 Visual Studio 窗口窗体中的面板上使用不透明度有什么技巧吗?

标签 c# .net winforms panel opacity

我最近开始探索 Visual Studio。 我试图创建一个幻灯片菜单。更具体地说,当用户按下按钮时,会在右侧弹出一个子菜单。为此,我放置了一个 Panel 来自行调整大小。除了功能之外,我还想添加更多设计并使 Panel 看起来有点褪色。

我知道 Visual Studio 中的 Panels 没有不透明度,但我在想是否有人知道如何实现它。我尝试了 Picture Box,但它也没有将 Opacity 作为属性。我避免使用 visual studio 提供的常规 Menu 对象,因为我想添加更多设计。有什么想法吗?

最佳答案

  1. 创建一个继承自 Panel 的类.
  2. 设置ControlStyle.Opaque使用 SetStyle 在构造函数中进行控制.

If true, the control is drawn opaque and the background is not painted.

  1. 覆盖 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.

  1. 创建一个 Opacity 属性,接受 0 到 100 之间的值,将用作背景的 alpha channel 。
  2. 覆盖 OnPaint并使用从 BackGroundColorOpacity 创建的启用 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);
    }
}

截图

enter image description here

关于c# - 在 Visual Studio 窗口窗体中的面板上使用不透明度有什么技巧吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400320/

相关文章:

c# - 如何使用 C# 在 Json 中通过键的名称获取值列表

c# - 如何在 ASP.NET Core 5 中使用 IdentityUser 和 IdentityRole 之间的隐式多对多

c# - 将组合框绑定(bind)到 2 个数据源 : Table & Enum

c# - 如何修复过时的 ILoggerFactory 方法?

c# - 无法以编程方式显示设置的 Winforms 文本框值

c# - 播放声音 : accessing length and position

c# - 尝试创建 NHibernate 和 FluentNHibernate 来连接 MySQL?

c# - 将内容正文添加到客户电子邮件

.net - 解析日期格式难以转换

c# - 进度条 C#