Ways to create a ListBox with transparent background

0

First of all I have to say that I have already created a ListBox with transparent background thanks to the contribution of another person in the English forum .

The problem is that even having obtained the result I was looking for I am not happy with the "botched" that I have done in the code and I would like to know if it can be done differently or close the .cs and I do not look at it anymore. everything that I have left of the project.

If anyone uses this code is free to replicate it or do what you want with it (you may fail the source because it is one that I installed):

using System.Drawing;
using System.Windows.Forms;

namespace RetroGameManager
{
    public partial class CustomListBox : ListBox
    {
        public CustomListBox()
        {
            Font = new Font("Orbitron", 11.25F, FontStyle.Bold, GraphicsUnit.Point, 0);
            ScrollAlwaysVisible = false;
            SetStyle(ControlStyles.SupportsTransparentBackColor |
                     ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint, true);
            BackColor = Color.FromArgb(100, 255, 255, 255);
        }

        protected override void OnMeasureItem(MeasureItemEventArgs e)
        {
            if (Site != null)
                return;
            if (e.Index > -1)
            {
                string item = Items[e.Index].ToString();
                SizeF sf = e.Graphics.MeasureString(item, Font, Width);
                e.ItemHeight = Font.Height + 2;
                e.ItemWidth = Width;
            }
        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            if (Site != null)
                return;
            if (e.Index > -1)
            {
                string item = Items[e.Index].ToString();
                if ((e.State & DrawItemState.Focus) != 0)
                {
                    Rectangle rect = new Rectangle
                    {
                        X = 0,
                        Y = 0,
                        Width = Width,
                        Height = e.Bounds.Top
                    };
                    Invalidate(rect);
                    rect.Y = e.Bounds.Bottom;
                    rect.Height = Height - rect.Y;
                    Invalidate(rect);
                    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 0, 0)), e.Bounds);
                }
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            int count = 0;
            foreach(string item in Items)
            {
                e.Graphics.DrawString(item, Font, new SolidBrush(Color.Black), 0, (Font.Height + 2) * count++);
            }
        }
    }
}

The effect it creates is this:

    
asked by Adrián Fernández 09.11.2018 в 18:39
source

0 answers