加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在Visual Studio窗体窗体中使用面板上的不透明度的任何技

发布时间:2020-12-16 01:21:56 所属栏目:百科 来源:网络整理
导读:我最近开始探索Visual Studio. 我试图创建一个幻灯片菜单.更具体地说,当用户按下按钮时,子菜单会弹出到右侧.为了实现这一点,我已经放置了一个Panel来调整自身的大小.除了功能,我想添加更多的设计,使面板显得有点褪色. 我知道Visual Studio中的Panels没有不透
我最近开始探索Visual Studio.
我试图创建一个幻灯片菜单.更具体地说,当用户按下按钮时,子菜单会弹出到右侧.为了实现这一点,我已经放置了一个Panel来调整自身的大小.除了功能,我想添加更多的设计,使面板显得有点褪色.

我知道Visual Studio中的Panels没有不透明性,但我在想是否有人知道如何实现它的方法技巧.我尝试了一个Picture Box但是它也没有Opacity作为属性.我避免使用visual studio提供的常规Menuobject,因为我想添加更多设计.有任何想法吗?

解决方法

>创建一个继承自Panel的类.
>在构造函数中设置ControlStyle.Opaque样式以进行控制.

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.

>创建一个不透明度属性,该属性接受0到100之间的值,这些值将用作背景的Alpha通道.
>覆盖OnPaint并使用从BackGroundColor和Opacity创建的支持Alpha的画笔填充背景.

完整代码

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读