背景透明的ListBox(C#.WinForm)

不知道大家有没有遇到过这种问题,C#中希望搞一个背景透明的ListBox,且文本居中,却发现VS里面自带的ListBox控件不支持背景透明,怎么办?

我们可以做一个自定义控件,重载里面的OnPaint函数,使ListBox支持背景透明

 

    /// <summary>
    /// 实现背景透明的ListBox,且文本居中
    /// 编写人:涂剑凯
    /// </summary>
    public class TransParentListBox : ListBox
    {
        public TransParentListBox()
        {
            //如果为 true,控件将自行绘制,而不是通过操作系统来绘制。
            //如果为 false,将不会引发 Paint 事件。此样式仅适用于派生自 Control 的类。
            this.SetStyle(ControlStyles.UserPaint, true);


            //如果为 true,控件接受 alpha 组件小于 255 的 BackColor 以模拟透明。
            //仅在 UserPaint 位设置为 true 并且父控件派生自 Control 时才模拟透明。
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            this.Invalidate();
            base.OnSelectedIndexChanged(e);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (this.Focused && this.SelectedItem != null)
            {
                //设置选中行背景颜色
                Rectangle itemRect = this.GetItemRectangle(this.SelectedIndex);
                //e.Graphics.FillRectangle(Brushes.Red, itemRect);
                e.Graphics.FillRectangle(Brushes.LightBlue, itemRect);
            }
            for (int i = 0; i < Items.Count; i++)
            {
                //设置绘制文字的格式
                StringFormat strFmt = new System.Drawing.StringFormat();
                strFmt.Alignment = StringAlignment.Center; //文本垂直居中
                strFmt.LineAlignment = StringAlignment.Center; //文本水平居中
                e.Graphics.DrawString(this.GetItemText(this.Items[i]), this.Font, new SolidBrush(this.ForeColor), this.GetItemRectangle(i), strFmt);

                //e.Graphics.DrawString(this.GetItemText(this.Items[i]), this.Font, new SolidBrush(this.ForeColor), this.GetItemRectangle(i));
            }



            base.OnPaint(e);
        }

    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值