C#重写控件使其透明背景

来源:互联网 发布:漫步者音响推荐知乎 编辑:程序博客网 时间:2024/05/16 13:57
  1. //这里用listbox为例子

  2. public partial class Mylistbox : ListBox
        {
            public Mylistbox()
            {
                InitializeComponent();
                this.SetStyle(ControlStyles.UserPaint, true);


                this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            }


            protected override void OnPaint(PaintEventArgs e)
            {
                if (this.Focused && this.SelectedItem != null)
                {


                    Rectangle itemRect = this.GetItemRectangle(this.SelectedIndex);


                    e.Graphics.FillRectangle(Brushes.Green, itemRect);


                }


                for (int i = 0; i < Items.Count; i++)
                {


                    e.Graphics.DrawString(this.GetItemText(this.Items[i]), this.Font,


                    new SolidBrush(this.ForeColor), this.GetItemRectangle(i));


                }


                base.OnPaint(e);


            }


            protected override void OnSelectedIndexChanged(EventArgs e)
            {


                this.Invalidate();


                base.OnSelectedIndexChanged(e);


            }


            
        }

1 0