using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace DTS.Common.Utilities { /// /// This class wraps the list items in the combo box /// public class CheckComboBoxItem { /// /// C'tor - creates a CheckComboBoxItem /// /// Label of the check box in the drop down list /// Initial value for the check box (true=checked) public CheckComboBoxItem(string text, bool initialCheckState) { CheckState = initialCheckState; Text = text; } /// /// Get or set the check value (true=checked) /// public bool CheckState { get; set; } = false; /// /// Gets the label of the check box /// public string Text { get; set; } = ""; /// /// User defined data /// public object Tag { get; set; } = null; /// /// This is used to keep the edit control portion of the combo box consistent /// /// public override string ToString() { return "Select Options"; } } /// /// Inherits from ComboBox and handles DrawItem and SelectedIndexChanged events to create an /// owner drawn combo box drop-down. The contents of the dropdown are rendered using the /// CheckBoxRenderer class. /// public partial class CheckComboBox : ComboBox { /// /// C'tor /// public CheckComboBox() { DrawMode = DrawMode.OwnerDrawFixed; DrawItem += CheckComboBox_DrawItem; SelectedIndexChanged += CheckComboBox_SelectedIndexChanged; SelectedText = "Select Options"; } /// /// Invoked when the selected index is changed on the dropdown. This sets the check state /// of the CheckComboBoxItem and fires the public event CheckStateChanged using the /// CheckComboBoxItem as the event sender. /// /// /// void CheckComboBox_SelectedIndexChanged(object sender, EventArgs e) { var item = (CheckComboBoxItem)SelectedItem; if (item == null) return; item.CheckState = !item.CheckState; if (CheckStateChanged != null) CheckStateChanged(item, e); } /// /// Invoked when the ComboBox has to render the drop-down items. /// /// /// void CheckComboBox_DrawItem(object sender, DrawItemEventArgs e) { // make sure the index is valid (sanity check) if (e.Index == -1) { return; } // test the item to see if its a CheckComboBoxItem if (!(Items[e.Index] is CheckComboBoxItem)) { // it's not, so just render it as a default string e.Graphics.DrawString( Items[e.Index].ToString(), Font, Brushes.Black, new Point(e.Bounds.X, e.Bounds.Y)); return; } // get the CheckComboBoxItem from the collection var box = (CheckComboBoxItem)Items[e.Index]; // render it CheckBoxRenderer.RenderMatchingApplicationState = true; CheckBoxRenderer.DrawCheckBox( e.Graphics, new Point(e.Bounds.X, e.Bounds.Y), e.Bounds, box.Text, Font, (e.State & DrawItemState.Focus) == 0, box.CheckState ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal); } /// /// Fired when the user clicks a check box item in the drop-down list /// public event EventHandler CheckStateChanged; } }