Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Drawing;
- using System.Drawing.Text;
- using System.Linq;
- using System.Windows.Forms;
- [DesignerCategory("Code")]
- [ToolboxItem(true), ToolboxBitmap(typeof(ComboBox))] // Generic: replace with custom Icon
- public class ComboBoxColorSelector : ComboBox
- {
- private Color defaultColor = Color.Transparent;
- public ComboBoxColorSelector() => InitializeComponent();
- private void InitializeComponent()
- {
- DropDownStyle = ComboBoxStyle.DropDownList;
- DrawMode = DrawMode.OwnerDrawVariable;
- FlatStyle = FlatStyle.Flat;
- FormattingEnabled = false;
- }
- // Read this Property value when a selection is made
- // This is the Color currently selected
- public Color SelectedColor { get; private set; }
- protected override void OnHandleCreated(EventArgs e)
- {
- base.OnHandleCreated(e);
- if (DesignMode || Items.Count > 0) return;
- Color[] colors =
- Enum.GetValues(typeof(KnownColor)).OfType<KnownColor>()
- .Select(kc => Color.FromKnownColor(kc)).ToArray();
- DisplayMember = "Name";
- DataSource = colors;
- }
- int previousFound = 0;
- protected override void OnKeyPress(KeyPressEventArgs e)
- {
- base.OnKeyPress(e);
- if (char.IsLetter(e.KeyChar)) {
- int found = FindString(e.KeyChar.ToString().ToUpper(), previousFound);
- if (found > -1) {
- previousFound = found;
- SelectedIndex = found;
- }
- else {
- previousFound = 0;
- }
- }
- }
- protected override void OnDrawItem(DrawItemEventArgs e)
- {
- e.DrawBackground();
- if (e.Index < 0) return;
- e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
- var itemColor = (Color)Items[e.Index];
- using (Brush itemBrush = new SolidBrush(itemColor))
- using (Brush textBrush = new SolidBrush(e.ForeColor)) {
- e.Graphics.FillRectangle(itemBrush, new Rectangle(new Point(e.Bounds.X + 1, e.Bounds.Y + 1), new Size(e.Bounds.Height - 1, e.Bounds.Height - 1)));
- e.Graphics.DrawString(itemColor.Name, e.Font, textBrush, new Point(e.Bounds.X + e.Bounds.Height + 10, e.Bounds.Y));
- }
- e.DrawFocusRectangle();
- base.OnDrawItem(e);
- }
- protected override void OnMeasureItem(MeasureItemEventArgs e)
- {
- e.ItemHeight = Font.Height + 4;
- base.OnMeasureItem(e);
- }
- protected override void OnSelectionChangeCommitted(EventArgs e)
- {
- if (SelectedIndex >= 0) SelectedColor = (Color)SelectedItem;
- base.OnSelectionChangeCommitted(e);
- }
- protected override void OnSelectedIndexChanged(EventArgs e)
- {
- if (SelectedIndex >= 0) SelectedColor = (Color)SelectedItem;
- base.OnSelectedIndexChanged(e);
- }
- protected override void OnParentForeColorChanged(EventArgs e)
- {
- base.OnParentForeColorChanged(e);
- if (this.Parent != null) defaultColor = this.Parent.ForeColor;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement