HamBook – Rev 54

Subversion Repositories:
Rev:
// Derived from https://stackoverflow.com/questions/63917294/custom-paint-in-toolstriptextbox

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace HamBook.Utilities.Controls
{
    [DesignerCategory("ToolStrip")]
    [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
    public class ScrollableToolStripComboBox : ToolStripComboBox
    {
        public ScrollableToolStripComboBox()
        {
            ComboBox.MouseWheel += ComboBox_MouseWheel;
        }

        /// <summary>
        ///     The image that will be displayed on the item.
        /// </summary>
        [Browsable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Category("Appearance")]
        [Description("The image associated with the object.")]
        public override Image Image
        {
            get => base.Image;
            set => base.Image = value;
        }

        public new ComboBoxStyle DropDownStyle
        {
            get => base.DropDownStyle;
            set => base.DropDownStyle = value;
        }

        [Browsable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Description("Mouse scrolling")]
        public event MouseEventHandler MouseWheel;

        private void ComboBox_MouseWheel(object sender, MouseEventArgs e)
        {
            MouseWheel?.Invoke(this, e);
        }

        protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent)
        {
            base.OnParentChanged(oldParent, newParent);

            if (newParent != null && newParent is ToolStripDropDownMenu)
            {
                newParent.Paint -= OnParentPaint;
                newParent.Paint += OnParentPaint;
            }

            if (oldParent != null)
                oldParent.Paint -= OnParentPaint;
        }

        private void OnParentPaint(object sender, PaintEventArgs e)
        {
            if (Image is null ||
                (sender is ContextMenuStrip cmnu &&
                 !cmnu.ShowImageMargin && !cmnu.ShowCheckMargin))
                return;

            var sz = Image.Size;
            var r = new Rectangle((Bounds.X - sz.Width - 7) / 2,
                (Bounds.Height - sz.Height) / 2 + Bounds.Y, sz.Width, sz.Height);

            if (RightToLeft == RightToLeft.Yes)
                r.X = Bounds.Right + r.Width - ContentRectangle.X;

            e.Graphics.DrawImage(Image, r);
        }
    }
}

Generated by GNU Enscript 1.6.5.90.