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

发布时间:2023-05-15 09:28:50

不知道大家有没有遇到过这样的问题,C#希望做一个背景透明的Listbox,文本居中,却发现VS自带的Listbox控件不支持背景透明。我该怎么办?

我们可以制作一个自定义控件,重载Onpaint函数,使ListBox支持透明的背景

/// <summary>    /// Listbox,背景透明,且文本居中    /// 作者:涂剑凯    /// </summary>    public class TransParentListBox : ListBox    {        public TransParentListBox()        {            //如果为 true,控件将自行绘制,而不是通过操作系统绘制。            //如果为 false,将不会引发 Paint 事件。            //如果为 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);        }    }

上一篇 c# 生成文字图片
下一篇 Codeforces Round #385 (Div. 2) -- B. Hongcow Solves A Puzzle (判断是否是矩形,水题)

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题