1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 // Copyright (c) 2004-2006 Novell, Inc.
23 // Jordi Mas i Hernandez, jordi@ximian.com
24 // Mike Kestner <mkestner@novell.com>
25 // Daniel Nauck (dna(at)mono-project(dot)de)
28 using System.Collections;
29 using System.ComponentModel;
30 using System.ComponentModel.Design;
31 using System.ComponentModel.Design.Serialization;
33 using System.Globalization;
34 using System.Reflection;
35 using System.Runtime.InteropServices;
37 namespace System.Windows.Forms
39 [DefaultProperty("Items")]
40 [DefaultEvent("SelectedIndexChanged")]
41 [Designer ("System.Windows.Forms.Design.ComboBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
43 [DefaultBindingProperty ("Text")]
44 [ClassInterface (ClassInterfaceType.AutoDispatch)]
47 public class ComboBox : ListControl
49 private DrawMode draw_mode = DrawMode.Normal;
50 private ComboBoxStyle dropdown_style;
51 private int dropdown_width = -1;
52 private int selected_index = -1;
53 private ObjectCollection items;
54 private bool suspend_ctrlupdate;
55 private int maxdrop_items = 8;
56 private bool integral_height = true;
58 private int max_length;
59 private ComboListBox listbox_ctrl;
60 private ComboTextBox textbox_ctrl;
61 private bool process_textchanged_event = true;
62 private bool item_height_specified;
63 private int item_height;
64 private int requested_height = -1;
65 private Hashtable item_heights;
66 private bool show_dropdown_button;
67 private ButtonState button_state = ButtonState.Normal;
68 private bool dropped_down;
69 private Rectangle text_area;
70 private Rectangle button_area;
71 private Rectangle listbox_area;
72 private const int button_width = 16;
73 bool drop_down_button_entered;
75 private AutoCompleteStringCollection auto_complete_custom_source = null;
76 private AutoCompleteMode auto_complete_mode = AutoCompleteMode.None;
77 private AutoCompleteSource auto_complete_source = AutoCompleteSource.None;
78 private int drop_down_height;
79 private FlatStyle flat_style;
83 public class ChildAccessibleObject : AccessibleObject {
85 public ChildAccessibleObject (ComboBox owner, IntPtr handle)
90 public override string Name {
99 items = new ObjectCollection (this);
100 DropDownStyle = ComboBoxStyle.DropDown;
101 item_height = FontHeight + 2;
102 background_color = ThemeEngine.Current.ColorWindow;
103 border_style = BorderStyle.None;
106 drop_down_height = 106;
107 flat_style = FlatStyle.Standard;
111 MouseDown += new MouseEventHandler (OnMouseDownCB);
112 MouseUp += new MouseEventHandler (OnMouseUpCB);
113 MouseMove += new MouseEventHandler (OnMouseMoveCB);
114 MouseWheel += new MouseEventHandler (OnMouseWheelCB);
115 MouseEnter += new EventHandler (OnMouseEnter);
116 MouseLeave += new EventHandler (OnMouseLeave);
117 KeyDown +=new KeyEventHandler(OnKeyDownCB);
123 [EditorBrowsable (EditorBrowsableState.Never)]
124 public new event EventHandler BackgroundImageChanged {
125 add { base.BackgroundImageChanged += value; }
126 remove { base.BackgroundImageChanged -= value; }
132 [EditorBrowsable (EditorBrowsableState.Never)]
133 public new event EventHandler BackgroundImageLayoutChanged
135 add { base.BackgroundImageLayoutChanged += value; }
136 remove { base.BackgroundImageLayoutChanged -= value; }
140 [EditorBrowsable (EditorBrowsableState.Never)]
141 public new event EventHandler DoubleClick
143 add { base.DoubleClick += value; }
144 remove { base.DoubleClick -= value; }
148 static object DrawItemEvent = new object ();
149 static object DropDownEvent = new object ();
150 static object DropDownStyleChangedEvent = new object ();
151 static object MeasureItemEvent = new object ();
152 static object SelectedIndexChangedEvent = new object ();
153 static object SelectionChangeCommittedEvent = new object ();
155 static object DropDownClosedEvent = new object ();
156 static object TextUpdateEvent = new object ();
159 public event DrawItemEventHandler DrawItem {
160 add { Events.AddHandler (DrawItemEvent, value); }
161 remove { Events.RemoveHandler (DrawItemEvent, value); }
164 public event EventHandler DropDown {
165 add { Events.AddHandler (DropDownEvent, value); }
166 remove { Events.RemoveHandler (DropDownEvent, value); }
169 public event EventHandler DropDownClosed
171 add { Events.AddHandler (DropDownClosedEvent, value); }
172 remove { Events.RemoveHandler (DropDownClosedEvent, value); }
176 public event EventHandler DropDownStyleChanged {
177 add { Events.AddHandler (DropDownStyleChangedEvent, value); }
178 remove { Events.RemoveHandler (DropDownStyleChangedEvent, value); }
181 public event MeasureItemEventHandler MeasureItem {
182 add { Events.AddHandler (MeasureItemEvent, value); }
183 remove { Events.RemoveHandler (MeasureItemEvent, value); }
187 [EditorBrowsable (EditorBrowsableState.Never)]
188 public new event EventHandler PaddingChanged
190 add { base.PaddingChanged += value; }
191 remove { base.PaddingChanged -= value; }
196 [EditorBrowsable (EditorBrowsableState.Never)]
197 public new event PaintEventHandler Paint {
198 add { base.Paint += value; }
199 remove { base.Paint -= value; }
202 public event EventHandler SelectedIndexChanged {
203 add { Events.AddHandler (SelectedIndexChangedEvent, value); }
204 remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
207 public event EventHandler SelectionChangeCommitted {
208 add { Events.AddHandler (SelectionChangeCommittedEvent, value); }
209 remove { Events.RemoveHandler (SelectionChangeCommittedEvent, value); }
212 public event EventHandler TextUpdate
214 add { Events.AddHandler (TextUpdateEvent, value); }
215 remove { Events.RemoveHandler (TextUpdateEvent, value); }
221 #region Public Properties
223 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
224 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
226 [EditorBrowsable (EditorBrowsableState.Always)]
228 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design,
229 "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
230 public AutoCompleteStringCollection AutoCompleteCustomSource {
232 if(auto_complete_custom_source == null) {
233 auto_complete_custom_source = new AutoCompleteStringCollection ();
234 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
236 return auto_complete_custom_source;
239 if(auto_complete_custom_source == value)
242 if(auto_complete_custom_source != null) //remove eventhandler from old collection
243 auto_complete_custom_source.CollectionChanged -= new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
245 auto_complete_custom_source = value;
247 if(auto_complete_custom_source != null)
248 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
250 SetTextBoxAutoCompleteData ();
254 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
256 [EditorBrowsable (EditorBrowsableState.Always)]
257 [DefaultValue (AutoCompleteMode.None)]
258 public AutoCompleteMode AutoCompleteMode {
259 get { return auto_complete_mode; }
261 if(auto_complete_mode == value)
264 if((value < AutoCompleteMode.None) || (value > AutoCompleteMode.SuggestAppend))
265 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteMode", value));
267 auto_complete_mode = value;
268 SetTextBoxAutoCompleteData ();
272 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
274 [EditorBrowsable (EditorBrowsableState.Always)]
275 [DefaultValue (AutoCompleteSource.None)]
276 public AutoCompleteSource AutoCompleteSource {
277 get { return auto_complete_source; }
279 if(auto_complete_source == value)
282 if(!Enum.IsDefined (typeof (AutoCompleteSource), value))
283 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteSource", value));
285 auto_complete_source = value;
286 SetTextBoxAutoCompleteData ();
290 void SetTextBoxAutoCompleteData ()
292 if (textbox_ctrl == null)
295 textbox_ctrl.AutoCompleteMode = auto_complete_mode;
297 if (auto_complete_source == AutoCompleteSource.ListItems) {
298 textbox_ctrl.AutoCompleteSource = AutoCompleteSource.CustomSource;
299 textbox_ctrl.AutoCompleteCustomSource = null;
300 textbox_ctrl.AutoCompleteInternalSource = this;
302 textbox_ctrl.AutoCompleteSource = auto_complete_source;
303 textbox_ctrl.AutoCompleteCustomSource = auto_complete_custom_source;
304 textbox_ctrl.AutoCompleteInternalSource = null;
308 public override Color BackColor {
309 get { return base.BackColor; }
311 if (base.BackColor == value)
313 base.BackColor = value;
319 [EditorBrowsable (EditorBrowsableState.Never)]
320 public override Image BackgroundImage {
321 get { return base.BackgroundImage; }
323 if (base.BackgroundImage == value)
325 base.BackgroundImage = value;
332 [EditorBrowsable (EditorBrowsableState.Never)]
333 public override ImageLayout BackgroundImageLayout {
334 get { return base.BackgroundImageLayout; }
335 set { base.BackgroundImageLayout = value; }
339 protected override CreateParams CreateParams {
340 get { return base.CreateParams;}
344 [DefaultValue ((string)null)]
345 [AttributeProvider (typeof (IListSource))]
346 [RefreshProperties (RefreshProperties.Repaint)]
347 [MWFCategory("Data")]
348 public new object DataSource {
349 get { return base.DataSource; }
350 set { base.DataSource = value; }
354 protected override Size DefaultSize {
355 get { return new Size (121, 21); }
358 [RefreshProperties(RefreshProperties.Repaint)]
359 [DefaultValue (DrawMode.Normal)]
360 [MWFCategory("Behavior")]
361 public DrawMode DrawMode {
362 get { return draw_mode; }
364 if (!Enum.IsDefined (typeof (DrawMode), value))
365 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for DrawMode", value));
367 if (draw_mode == value)
370 if (draw_mode == DrawMode.OwnerDrawVariable)
373 if (draw_mode == DrawMode.OwnerDrawVariable)
374 item_heights = new Hashtable ();
382 [EditorBrowsable (EditorBrowsableState.Always)]
383 [MWFCategory("Behavior")]
384 public int DropDownHeight {
386 return drop_down_height;
390 throw new ArgumentOutOfRangeException ("DropDownHeight", "DropDownHeight must be greater than 0.");
392 drop_down_height = value;
393 IntegralHeight = false;
398 [DefaultValue (ComboBoxStyle.DropDown)]
399 [RefreshProperties(RefreshProperties.Repaint)]
400 [MWFCategory("Appearance")]
401 public ComboBoxStyle DropDownStyle {
402 get { return dropdown_style; }
404 if (!Enum.IsDefined (typeof (ComboBoxStyle), value))
405 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for ComboBoxStyle", value));
407 if (dropdown_style == value)
412 if (dropdown_style == ComboBoxStyle.Simple) {
413 if (listbox_ctrl != null) {
414 Controls.RemoveImplicit (listbox_ctrl);
415 listbox_ctrl.Dispose ();
420 dropdown_style = value;
422 if (dropdown_style == ComboBoxStyle.DropDownList && textbox_ctrl != null) {
423 Controls.RemoveImplicit (textbox_ctrl);
424 textbox_ctrl.Dispose ();
428 if (dropdown_style == ComboBoxStyle.Simple) {
429 show_dropdown_button = false;
431 CreateComboListBox ();
432 Controls.AddImplicit (listbox_ctrl);
433 listbox_ctrl.Visible = true;
435 // This should give us a 150 default height
436 // for Simple mode if size hasn't been set
437 // (DefaultSize doesn't work for us in this case)
438 if (requested_height == -1)
439 requested_height = 150;
441 show_dropdown_button = true;
442 button_state = ButtonState.Normal;
445 if (dropdown_style != ComboBoxStyle.DropDownList && textbox_ctrl == null) {
446 textbox_ctrl = new ComboTextBox (this);
447 object selected_item = SelectedItem;
448 if (selected_item != null)
449 textbox_ctrl.Text = GetItemText (selected_item);
450 textbox_ctrl.BorderStyle = BorderStyle.None;
451 textbox_ctrl.TextChanged += new EventHandler (OnTextChangedEdit);
452 textbox_ctrl.KeyPress += new KeyPressEventHandler (OnTextKeyPress);
453 textbox_ctrl.Click += new EventHandler (OnTextBoxClick);
454 textbox_ctrl.ContextMenu = ContextMenu;
456 if (IsHandleCreated == true)
457 Controls.AddImplicit (textbox_ctrl);
459 SetTextBoxAutoCompleteData ();
464 OnDropDownStyleChanged (EventArgs.Empty);
467 UpdateComboBoxBounds ();
472 [MWFCategory("Behavior")]
473 public int DropDownWidth {
475 if (dropdown_width == -1)
478 return dropdown_width;
481 if (dropdown_width == value)
486 throw new ArgumentOutOfRangeException ("DropDownWidth",
487 "The DropDownWidth value is less than one.");
489 throw new ArgumentException ("The DropDownWidth value is less than one.");
492 dropdown_width = value;
497 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
498 public bool DroppedDown {
500 if (dropdown_style == ComboBoxStyle.Simple)
506 if (dropdown_style == ComboBoxStyle.Simple || dropped_down == value)
512 listbox_ctrl.Hide ();
517 [DefaultValue (FlatStyle.Standard)]
519 [MWFCategory("Appearance")]
520 public FlatStyle FlatStyle {
521 get { return flat_style; }
523 if (!Enum.IsDefined (typeof (FlatStyle), value))
524 throw new InvalidEnumArgumentException ("FlatStyle", (int) value, typeof (FlatStyle));
533 public override bool Focused {
534 get { return base.Focused; }
537 public override Color ForeColor {
538 get { return base.ForeColor; }
540 if (base.ForeColor == value)
542 base.ForeColor = value;
547 [DefaultValue (true)]
549 [MWFCategory("Behavior")]
550 public bool IntegralHeight {
551 get { return integral_height; }
553 if (integral_height == value)
555 integral_height = value;
556 UpdateComboBoxBounds ();
562 [MWFCategory("Behavior")]
563 public int ItemHeight {
565 if (item_height == -1) {
566 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
567 item_height = (int) sz.Height;
574 throw new ArgumentOutOfRangeException ("ItemHeight",
575 "The item height value is less than one.");
577 throw new ArgumentException ("The item height value is less than one.");
580 item_height_specified = true;
583 UpdateComboBoxBounds ();
589 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
591 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
593 [MergableProperty (false)]
595 [MWFCategory("Data")]
596 public ComboBox.ObjectCollection Items {
597 get { return items; }
602 [MWFCategory("Behavior")]
603 public int MaxDropDownItems {
604 get { return maxdrop_items; }
606 if (maxdrop_items == value)
608 maxdrop_items = value;
613 public override Size MaximumSize {
614 get { return base.MaximumSize; }
616 base.MaximumSize = new Size (value.Width, 0);
623 [MWFCategory("Behavior")]
624 public int MaxLength {
625 get { return max_length; }
627 if (max_length == value)
632 if (dropdown_style != ComboBoxStyle.DropDownList) {
636 textbox_ctrl.MaxLength = value;
642 public override Size MinimumSize {
643 get { return base.MinimumSize; }
645 base.MinimumSize = new Size (value.Width, 0);
649 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
650 [EditorBrowsable (EditorBrowsableState.Never)]
652 public new Padding Padding {
653 get { return base.Padding; }
654 set { base.Padding = value; }
658 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
660 public int PreferredHeight {
661 get { return Font.Height + 8; }
665 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
666 public override int SelectedIndex {
667 get { return selected_index; }
669 if (selected_index == value)
672 if (value <= -2 || value >= Items.Count)
673 throw new ArgumentOutOfRangeException ("SelectedIndex");
674 selected_index = value;
676 if (dropdown_style != ComboBoxStyle.DropDownList) {
678 SetControlText (string.Empty, false);
680 SetControlText (GetItemText (Items [value]), false);
683 if (DropDownStyle == ComboBoxStyle.DropDownList)
686 if (listbox_ctrl != null)
687 listbox_ctrl.HighlightedIndex = value;
689 OnSelectedValueChanged (new EventArgs ());
690 OnSelectedIndexChanged (new EventArgs ());
691 OnSelectedItemChanged (new EventArgs ());
696 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
698 public object SelectedItem {
699 get { return selected_index == -1 ? null : Items [selected_index]; }
701 object item = selected_index == -1 ? null : Items [selected_index];
708 SelectedIndex = Items.IndexOf (value);
713 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
714 public string SelectedText {
716 if (dropdown_style == ComboBoxStyle.DropDownList)
719 string retval = textbox_ctrl.SelectedText;
722 // On 1.1, the textbox will return null, combobox returns ""
723 if (retval == null && !textbox_ctrl.IsHandleCreated)
729 if (dropdown_style == ComboBoxStyle.DropDownList)
731 textbox_ctrl.SelectedText = value;
736 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
737 public int SelectionLength {
739 if (dropdown_style == ComboBoxStyle.DropDownList)
742 int result = textbox_ctrl.SelectionLength;
743 return result == -1 ? 0 : result;
746 if (dropdown_style == ComboBoxStyle.DropDownList)
748 if (textbox_ctrl.SelectionLength == value)
750 textbox_ctrl.SelectionLength = value;
755 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
756 public int SelectionStart {
758 if (dropdown_style == ComboBoxStyle.DropDownList)
760 return textbox_ctrl.SelectionStart;
763 if (dropdown_style == ComboBoxStyle.DropDownList)
765 if (textbox_ctrl.SelectionStart == value)
767 textbox_ctrl.SelectionStart = value;
771 [DefaultValue (false)]
772 [MWFCategory("Behavior")]
774 get { return sorted; }
789 public override string Text {
791 if (dropdown_style != ComboBoxStyle.DropDownList) {
792 if (textbox_ctrl != null) {
793 return textbox_ctrl.Text;
797 if (SelectedItem != null)
798 return GetItemText (SelectedItem);
804 if (SelectedIndex == -1) {
805 if (dropdown_style != ComboBoxStyle.DropDownList)
806 SetControlText (string.Empty, false);
813 // do nothing if value exactly matches text of selected item
814 if (SelectedItem != null && string.Compare (value, GetItemText (SelectedItem), false, CultureInfo.CurrentCulture) == 0)
817 // find exact match using case-sensitive comparison, and if does
818 // not result in any match then use case-insensitive comparison
819 int index = FindStringExact (value, -1, false);
821 index = FindStringExact (value, -1, true);
824 SelectedIndex = index;
828 if (dropdown_style != ComboBoxStyle.DropDownList)
829 textbox_ctrl.Text = GetItemText (value);
833 #endregion Public Properties
835 #region Internal Properties
836 internal Rectangle ButtonArea {
837 get { return button_area; }
840 internal Rectangle TextArea {
841 get { return text_area; }
845 #region UIA Framework Properties
847 internal TextBox UIATextBox {
848 get { return textbox_ctrl; }
851 #endregion UIA Framework Properties
853 #region Public Methods
855 [Obsolete ("This method has been deprecated")]
857 protected virtual void AddItemsCore (object[] value)
862 public void BeginUpdate ()
864 suspend_ctrlupdate = true;
868 protected override AccessibleObject CreateAccessibilityInstance ()
870 return base.CreateAccessibilityInstance ();
873 protected override void CreateHandle ()
875 base.CreateHandle ();
879 protected override void Dispose (bool disposing)
882 if (listbox_ctrl != null) {
883 listbox_ctrl.Dispose ();
884 Controls.RemoveImplicit (listbox_ctrl);
888 if (textbox_ctrl != null) {
889 Controls.RemoveImplicit (textbox_ctrl);
890 textbox_ctrl.Dispose ();
895 base.Dispose (disposing);
898 public void EndUpdate ()
900 suspend_ctrlupdate = false;
905 public int FindString (string s)
907 return FindString (s, -1);
910 public int FindString (string s, int startIndex)
912 if (s == null || Items.Count == 0)
916 if (startIndex < -1 || startIndex >= Items.Count)
918 if (startIndex < -1 || startIndex >= Items.Count - 1)
920 throw new ArgumentOutOfRangeException ("startIndex");
924 if (i == (Items.Count - 1))
929 if (string.Compare (s, 0, GetItemText (Items [i]), 0, s.Length, true) == 0)
931 if (i == (Items.Count - 1))
933 } while (i != startIndex);
938 public int FindStringExact (string s)
940 return FindStringExact (s, -1);
943 public int FindStringExact (string s, int startIndex)
945 return FindStringExact (s, startIndex, true);
948 private int FindStringExact (string s, int startIndex, bool ignoreCase)
950 if (s == null || Items.Count == 0)
954 if (startIndex < -1 || startIndex >= Items.Count)
956 if (startIndex < -1 || startIndex >= Items.Count - 1)
958 throw new ArgumentOutOfRangeException ("startIndex");
962 if (i == (Items.Count - 1))
967 if (string.Compare (s, GetItemText (Items [i]), ignoreCase, CultureInfo.CurrentCulture) == 0)
969 if (i == (Items.Count - 1))
971 } while (i != startIndex);
976 public int GetItemHeight (int index)
978 if (DrawMode == DrawMode.OwnerDrawVariable && IsHandleCreated) {
980 if (index < 0 || index >= Items.Count )
981 throw new ArgumentOutOfRangeException ("The item height value is less than zero");
983 object item = Items [index];
984 if (item_heights.Contains (item))
985 return (int) item_heights [item];
987 MeasureItemEventArgs args = new MeasureItemEventArgs (DeviceContext, index, ItemHeight);
988 OnMeasureItem (args);
989 item_heights [item] = args.ItemHeight;
990 return args.ItemHeight;
996 protected override bool IsInputKey (Keys keyData)
998 switch (keyData & ~Keys.Modifiers) {
1014 protected override void OnBackColorChanged (EventArgs e)
1016 base.OnBackColorChanged (e);
1018 if (textbox_ctrl != null)
1019 textbox_ctrl.BackColor = BackColor;
1022 protected override void OnDataSourceChanged (EventArgs e)
1024 base.OnDataSourceChanged (e);
1027 if (DataSource == null || DataManager == null) {
1031 SelectedIndex = DataManager.Position;
1035 protected override void OnDisplayMemberChanged (EventArgs e)
1037 base.OnDisplayMemberChanged (e);
1039 if (DataManager == null)
1042 if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1043 SetControlText (GetItemText (Items [selected_index]), true);
1045 if (!IsHandleCreated)
1048 SelectedIndex = DataManager.Position;
1052 protected virtual void OnDrawItem (DrawItemEventArgs e)
1055 case DrawMode.OwnerDrawFixed:
1056 case DrawMode.OwnerDrawVariable:
1057 DrawItemEventHandler eh = (DrawItemEventHandler)(Events [DrawItemEvent]);
1062 ThemeEngine.Current.DrawComboBoxItem (this, e);
1067 protected virtual void OnDropDown (EventArgs e)
1069 EventHandler eh = (EventHandler)(Events [DropDownEvent]);
1075 protected virtual void OnDropDownClosed (EventArgs e)
1077 EventHandler eh = (EventHandler) Events [DropDownClosedEvent];
1083 protected virtual void OnDropDownStyleChanged (EventArgs e)
1085 EventHandler eh = (EventHandler)(Events [DropDownStyleChangedEvent]);
1090 protected override void OnFontChanged (EventArgs e)
1092 base.OnFontChanged (e);
1094 if (textbox_ctrl != null)
1095 textbox_ctrl.Font = Font;
1097 if (!item_height_specified) {
1098 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
1099 item_height = (int) sz.Height;
1103 UpdateComboBoxBounds ();
1108 protected override void OnForeColorChanged (EventArgs e)
1110 base.OnForeColorChanged (e);
1111 if (textbox_ctrl != null)
1112 textbox_ctrl.ForeColor = ForeColor;
1115 [EditorBrowsable(EditorBrowsableState.Advanced)]
1116 protected override void OnGotFocus (EventArgs e)
1118 if (dropdown_style == ComboBoxStyle.DropDownList) {
1119 // We draw DDL styles manually, so they require a
1120 // refresh to have their selection drawn
1124 if (textbox_ctrl != null) {
1125 textbox_ctrl.SetSelectable (false);
1126 textbox_ctrl.ShowSelection = true;
1127 textbox_ctrl.ActivateCaret (true);
1128 textbox_ctrl.SelectAll ();
1131 base.OnGotFocus (e);
1134 [EditorBrowsable(EditorBrowsableState.Advanced)]
1135 protected override void OnLostFocus (EventArgs e)
1137 if (dropdown_style == ComboBoxStyle.DropDownList) {
1138 // We draw DDL styles manually, so they require a
1139 // refresh to have their selection drawn
1143 if (listbox_ctrl != null && dropped_down) {
1144 listbox_ctrl.HideWindow ();
1147 if (textbox_ctrl != null) {
1148 textbox_ctrl.SetSelectable (true);
1149 textbox_ctrl.ActivateCaret (false);
1150 textbox_ctrl.ShowSelection = false;
1151 textbox_ctrl.SelectionLength = 0;
1154 base.OnLostFocus (e);
1157 protected override void OnHandleCreated (EventArgs e)
1159 base.OnHandleCreated (e);
1161 SetBoundsInternal (Left, Top, Width, PreferredHeight, BoundsSpecified.None);
1163 if (textbox_ctrl != null)
1164 Controls.AddImplicit (textbox_ctrl);
1167 UpdateComboBoxBounds ();
1170 protected override void OnHandleDestroyed (EventArgs e)
1172 base.OnHandleDestroyed (e);
1175 protected override void OnKeyPress (KeyPressEventArgs e)
1177 if (dropdown_style == ComboBoxStyle.DropDownList) {
1178 int index = FindStringCaseInsensitive (e.KeyChar.ToString (), SelectedIndex + 1);
1180 SelectedIndex = index;
1181 if (DroppedDown) { //Scroll into view
1182 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1183 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1184 // Or, selecting an item earlier in the list.
1185 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1186 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1191 base.OnKeyPress (e);
1194 protected virtual void OnMeasureItem (MeasureItemEventArgs e)
1196 MeasureItemEventHandler eh = (MeasureItemEventHandler)(Events [MeasureItemEvent]);
1201 protected override void OnParentBackColorChanged (EventArgs e)
1203 base.OnParentBackColorChanged (e);
1206 protected override void OnResize (EventArgs e)
1209 if (listbox_ctrl != null)
1210 listbox_ctrl.CalcListBoxArea ();
1213 protected override void OnSelectedIndexChanged (EventArgs e)
1215 base.OnSelectedIndexChanged (e);
1217 EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
1222 protected virtual void OnSelectedItemChanged (EventArgs e)
1226 protected override void OnSelectedValueChanged (EventArgs e)
1228 base.OnSelectedValueChanged (e);
1231 protected virtual void OnSelectionChangeCommitted (EventArgs e)
1233 EventHandler eh = (EventHandler)(Events [SelectionChangeCommittedEvent]);
1238 protected override void RefreshItem (int index)
1240 if (index < 0 || index >= Items.Count)
1241 throw new ArgumentOutOfRangeException ("index");
1243 if (draw_mode == DrawMode.OwnerDrawVariable)
1244 item_heights.Remove (Items [index]);
1248 protected override void RefreshItems ()
1250 for (int i = 0; i < Items.Count; i++) {
1255 public override void ResetText ()
1257 Text = String.Empty;
1260 protected override bool ProcessKeyEventArgs (ref Message m)
1262 return base.ProcessKeyEventArgs (ref m);
1265 [EditorBrowsable (EditorBrowsableState.Advanced)]
1266 protected override void OnKeyDown (KeyEventArgs e)
1271 [EditorBrowsable (EditorBrowsableState.Advanced)]
1272 protected override void OnValidating (CancelEventArgs e)
1274 base.OnValidating (e);
1277 [EditorBrowsable (EditorBrowsableState.Advanced)]
1278 protected override void OnTextChanged (EventArgs e)
1280 base.OnTextChanged (e);
1284 protected virtual void OnTextUpdate (EventArgs e)
1286 EventHandler eh = (EventHandler) Events [TextUpdateEvent];
1291 protected override void OnMouseLeave (EventArgs e)
1294 if (flat_style == FlatStyle.Popup)
1297 base.OnMouseLeave (e);
1300 protected override void OnMouseEnter (EventArgs e)
1303 if (flat_style == FlatStyle.Popup)
1306 base.OnMouseEnter (e);
1311 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
1313 base.ScaleControl (factor, specified);
1317 public void Select (int start, int length)
1320 throw new ArgumentException ("Start cannot be less than zero");
1323 throw new ArgumentException ("length cannot be less than zero");
1325 if (dropdown_style == ComboBoxStyle.DropDownList)
1328 textbox_ctrl.Select (start, length);
1331 public void SelectAll ()
1333 if (dropdown_style == ComboBoxStyle.DropDownList)
1336 if (textbox_ctrl != null) {
1337 textbox_ctrl.ShowSelection = true;
1338 textbox_ctrl.SelectAll ();
1342 protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified)
1344 bool vertically_anchored = (Anchor & AnchorStyles.Top) != 0 && (Anchor & AnchorStyles.Bottom) != 0;
1345 bool vertically_docked = Dock == DockStyle.Left || Dock == DockStyle.Right || Dock == DockStyle.Fill;
1347 if ((specified & BoundsSpecified.Height) != 0 ||
1348 (specified == BoundsSpecified.None && (vertically_anchored || vertically_docked))) {
1350 requested_height = height;
1351 height = SnapHeight (height);
1354 base.SetBoundsCore (x, y, width, height, specified);
1357 protected override void SetItemCore (int index, object value)
1359 if (index < 0 || index >= Items.Count)
1362 Items[index] = value;
1365 protected override void SetItemsCore (IList value)
1370 Items.AddRange (value);
1376 public override string ToString ()
1378 return base.ToString () + ", Items.Count:" + Items.Count;
1381 protected override void WndProc (ref Message m)
1383 switch ((Msg) m.Msg) {
1385 case Msg.WM_KEYDOWN:
1386 Keys keys = (Keys) m.WParam.ToInt32 ();
1387 if (keys == Keys.Up || keys == Keys.Down)
1389 goto case Msg.WM_CHAR;
1391 if (textbox_ctrl != null)
1392 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1394 case Msg.WM_MOUSELEAVE:
1395 Point location = PointToClient (Control.MousePosition);
1396 if (ClientRectangle.Contains (location))
1402 base.WndProc (ref m);
1405 #endregion Public Methods
1407 #region Private Methods
1409 void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) {
1410 if(auto_complete_source == AutoCompleteSource.CustomSource) {
1411 //FIXME: handle add, remove and refresh events in AutoComplete algorithm.
1416 internal override bool InternalCapture {
1417 get { return Capture; }
1421 void LayoutComboBox ()
1423 int border = ThemeEngine.Current.Border3DSize.Width;
1425 text_area = ClientRectangle;
1426 text_area.Height = PreferredHeight;
1428 listbox_area = ClientRectangle;
1429 listbox_area.Y = text_area.Bottom + 3;
1430 listbox_area.Height -= (text_area.Height + 2);
1432 Rectangle prev_button_area = button_area;
1434 if (DropDownStyle == ComboBoxStyle.Simple)
1435 button_area = Rectangle.Empty;
1437 button_area = text_area;
1438 button_area.X = text_area.Right - button_width - border;
1439 button_area.Y = text_area.Y + border;
1440 button_area.Width = button_width;
1441 button_area.Height = text_area.Height - 2 * border;
1443 if (flat_style == FlatStyle.Popup || flat_style == FlatStyle.Flat) {
1444 button_area.Inflate (1, 1);
1446 button_area.Width -= 2;
1451 if (button_area != prev_button_area) {
1452 prev_button_area.Y -= border;
1453 prev_button_area.Width += border;
1454 prev_button_area.Height += 2 * border;
1455 Invalidate (prev_button_area);
1456 Invalidate (button_area);
1459 if (textbox_ctrl != null) {
1460 int text_border = border + 1;
1461 textbox_ctrl.Location = new Point (text_area.X + text_border, text_area.Y + text_border);
1462 textbox_ctrl.Width = text_area.Width - button_area.Width - text_border * 2;
1463 textbox_ctrl.Height = text_area.Height - text_border * 2;
1466 if (listbox_ctrl != null && dropdown_style == ComboBoxStyle.Simple) {
1467 listbox_ctrl.Location = listbox_area.Location;
1468 listbox_ctrl.CalcListBoxArea ();
1472 private void CreateComboListBox ()
1474 listbox_ctrl = new ComboListBox (this);
1475 listbox_ctrl.HighlightedIndex = SelectedIndex;
1478 internal void Draw (Rectangle clip, Graphics dc)
1480 Theme theme = ThemeEngine.Current;
1481 FlatStyle style = FlatStyle.Standard;
1482 bool is_flat = false;
1485 style = this.FlatStyle;
1486 is_flat = style == FlatStyle.Flat || style == FlatStyle.Popup;
1489 theme.ComboBoxDrawBackground (this, dc, clip, style);
1491 int border = theme.Border3DSize.Width;
1493 // No edit control, we paint the edit ourselves
1494 if (dropdown_style == ComboBoxStyle.DropDownList) {
1495 DrawItemState state = DrawItemState.None;
1496 Rectangle item_rect = text_area;
1497 item_rect.X += border;
1498 item_rect.Y += border;
1499 item_rect.Width -= (button_area.Width + 2 * border);
1500 item_rect.Height -= 2 * border;
1503 state = DrawItemState.Selected;
1504 state |= DrawItemState.Focus;
1507 state |= DrawItemState.ComboBoxEdit;
1508 OnDrawItem (new DrawItemEventArgs (dc, Font, item_rect, SelectedIndex, state, ForeColor, BackColor));
1511 if (show_dropdown_button) {
1512 ButtonState current_state;
1514 current_state = button_state;
1516 current_state = ButtonState.Inactive;
1518 if (is_flat || theme.ComboBoxNormalDropDownButtonHasTransparentBackground (this, current_state))
1519 dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), button_area);
1522 theme.DrawFlatStyleComboButton (dc, button_area, current_state);
1524 theme.ComboBoxDrawNormalDropDownButton (this, dc, clip, button_area, current_state);
1529 internal bool DropDownButtonEntered {
1530 get { return drop_down_button_entered; }
1532 if (drop_down_button_entered == value)
1534 drop_down_button_entered = value;
1535 if (ThemeEngine.Current.ComboBoxDropDownButtonHasHotElementStyle (this))
1536 Invalidate (button_area);
1540 internal void DropDownListBox ()
1542 DropDownButtonEntered = false;
1544 if (DropDownStyle == ComboBoxStyle.Simple)
1547 if (listbox_ctrl == null)
1548 CreateComboListBox ();
1550 listbox_ctrl.Location = PointToScreen (new Point (text_area.X, text_area.Y + text_area.Height));
1552 FindMatchOrSetIndex(SelectedIndex);
1554 if (listbox_ctrl.ShowWindow ())
1555 dropped_down = true;
1557 button_state = ButtonState.Pushed;
1558 if (dropdown_style == ComboBoxStyle.DropDownList)
1559 Invalidate (text_area);
1562 internal void DropDownListBoxFinished ()
1564 if (DropDownStyle == ComboBoxStyle.Simple)
1567 FindMatchOrSetIndex (SelectedIndex);
1568 button_state = ButtonState.Normal;
1569 Invalidate (button_area);
1570 dropped_down = false;
1572 OnDropDownClosed (EventArgs.Empty);
1575 * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
1576 * this causes the popup to appear under the main form. This is horrible but necessary
1579 // If the user opens a new form in an event, it will close our dropdown,
1580 // so we need a null check here
1581 if (listbox_ctrl != null) {
1582 listbox_ctrl.Dispose ();
1583 listbox_ctrl = null;
1587 private int FindStringCaseInsensitive (string search)
1589 if (search.Length == 0) {
1593 for (int i = 0; i < Items.Count; i++)
1595 if (String.Compare (GetItemText (Items[i]), 0, search, 0, search.Length, true) == 0)
1602 // Search in the list for the substring, starting the search at the list
1603 // position specified, the search wraps thus covering all the list.
1604 internal int FindStringCaseInsensitive (string search, int start_index)
1606 if (search.Length == 0) {
1609 // Accept from first item to after last item. i.e. all cases of (SelectedIndex+1).
1610 if (start_index < 0 || start_index > Items.Count)
1611 throw new ArgumentOutOfRangeException("start_index");
1613 for (int i = 0; i < Items.Count; i++) {
1614 int index = (i + start_index) % Items.Count;
1615 if (String.Compare (GetItemText (Items [index]), 0, search, 0, search.Length, true) == 0)
1622 internal override bool IsInputCharInternal (char charCode)
1627 internal override ContextMenu ContextMenuInternal {
1629 return base.ContextMenuInternal;
1632 base.ContextMenuInternal = value;
1633 if (textbox_ctrl != null) {
1634 textbox_ctrl.ContextMenu = value;
1639 internal void RestoreContextMenu ()
1641 textbox_ctrl.RestoreContextMenu ();
1644 private void OnKeyDownCB(object sender, KeyEventArgs e)
1646 if (Items.Count == 0)
1653 FindMatchOrSetIndex(Math.Max(SelectedIndex - 1, 0));
1656 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1657 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1661 if ((e.Modifiers & Keys.Alt) == Keys.Alt)
1664 FindMatchOrSetIndex(Math.Min(SelectedIndex + 1, Items.Count - 1));
1667 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1668 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1672 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1676 SelectedIndex = Math.Max (SelectedIndex - offset, 0);
1679 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1680 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1684 if (SelectedIndex == -1) {
1686 if (dropdown_style != ComboBoxStyle.Simple)
1690 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1694 SelectedIndex = Math.Min (SelectedIndex + offset, Items.Count - 1);
1697 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1698 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1703 DropDownListBoxFinished ();
1707 if (dropdown_style == ComboBoxStyle.DropDownList) {
1711 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1712 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1717 if (dropdown_style == ComboBoxStyle.DropDownList) {
1718 SelectedIndex = Items.Count - 1;
1721 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1722 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1731 // If no item is currently selected, and an item is found matching the text
1732 // in the textbox, then selected that item. Otherwise the item at the given
1733 // index is selected.
1734 private void FindMatchOrSetIndex(int index)
1737 if (SelectedIndex == -1 && Text.Length != 0)
1738 match = FindStringCaseInsensitive(Text);
1740 SelectedIndex = match;
1742 SelectedIndex = index;
1745 void OnMouseDownCB (object sender, MouseEventArgs e)
1748 if (DropDownStyle == ComboBoxStyle.DropDownList)
1749 area = ClientRectangle;
1753 if (area.Contains (e.X, e.Y)) {
1754 if (Items.Count > 0)
1757 button_state = ButtonState.Pushed;
1758 OnDropDown (EventArgs.Empty);
1761 Invalidate (button_area);
1767 void OnMouseEnter (object sender, EventArgs e)
1769 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this))
1773 void OnMouseLeave (object sender, EventArgs e)
1775 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this)) {
1776 drop_down_button_entered = false;
1779 if (show_dropdown_button)
1780 DropDownButtonEntered = false;
1784 void OnMouseMoveCB (object sender, MouseEventArgs e)
1786 if (show_dropdown_button && !dropped_down)
1787 DropDownButtonEntered = button_area.Contains (e.Location);
1789 if (DropDownStyle == ComboBoxStyle.Simple)
1792 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1793 Point location = listbox_ctrl.PointToClient (Control.MousePosition);
1794 if (listbox_ctrl.ClientRectangle.Contains (location))
1795 listbox_ctrl.Capture = true;
1799 void OnMouseUpCB (object sender, MouseEventArgs e)
1803 button_state = ButtonState.Normal;
1804 Invalidate (button_area);
1806 OnClick (EventArgs.Empty);
1809 listbox_ctrl.Capture = true;
1812 private void OnMouseWheelCB (object sender, MouseEventArgs me)
1814 if (Items.Count == 0)
1817 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1818 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
1819 listbox_ctrl.Scroll (-lines);
1821 int lines = me.Delta / 120;
1822 int index = SelectedIndex - lines;
1825 else if (index >= Items.Count)
1826 index = Items.Count - 1;
1827 SelectedIndex = index;
1831 internal override void OnPaintInternal (PaintEventArgs pevent)
1833 if (suspend_ctrlupdate)
1836 Draw (ClientRectangle, pevent.Graphics);
1839 private void OnTextBoxClick (object sender, EventArgs e)
1844 private void OnTextChangedEdit (object sender, EventArgs e)
1846 if (process_textchanged_event == false)
1849 int item = FindStringCaseInsensitive (textbox_ctrl.Text);
1852 // Setting base.Text below will raise this event
1853 // if we found something
1854 OnTextChanged (EventArgs.Empty);
1858 // TODO: THIS IS BROKEN-ISH
1859 // I don't think we should hilight, and setting the top item does weirdness
1860 // when there is no scrollbar
1862 if (listbox_ctrl != null) {
1863 listbox_ctrl.SetTopItem (item);
1864 listbox_ctrl.HighlightedIndex = item;
1867 base.Text = textbox_ctrl.Text;
1870 private void OnTextKeyPress (object sender, KeyPressEventArgs e)
1872 selected_index = -1;
1875 internal void SetControlText (string s, bool suppressTextChanged)
1877 if (suppressTextChanged)
1878 process_textchanged_event = false;
1880 textbox_ctrl.Text = s;
1881 textbox_ctrl.SelectAll ();
1882 process_textchanged_event = true;
1885 void UpdateComboBoxBounds ()
1887 if (requested_height == -1)
1890 // Save the requested height since set bounds can destroy it
1891 int save_height = requested_height;
1892 SetBounds (bounds.X, bounds.Y, bounds.Width, SnapHeight (requested_height),
1893 BoundsSpecified.Height);
1894 requested_height = save_height;
1897 int SnapHeight (int height)
1899 if (DropDownStyle == ComboBoxStyle.Simple && height > PreferredHeight) {
1900 if (IntegralHeight) {
1901 int border = ThemeEngine.Current.Border3DSize.Height;
1902 int lb_height = (height - PreferredHeight - 2) - border * 2;
1903 if (lb_height > ItemHeight) {
1904 int partial = (lb_height) % ItemHeight;
1906 } else if (lb_height < ItemHeight)
1907 height = PreferredHeight;
1910 height = PreferredHeight;
1915 private void UpdatedItems ()
1917 if (listbox_ctrl != null) {
1918 listbox_ctrl.UpdateLastVisibleItem ();
1919 listbox_ctrl.CalcListBoxArea ();
1920 listbox_ctrl.Refresh ();
1924 #endregion Private Methods
1926 [ListBindableAttribute (false)]
1927 public class ObjectCollection : IList, ICollection, IEnumerable
1930 private ComboBox owner;
1931 internal ArrayList object_items = new ArrayList ();
1933 #region UIA Framework Events
1937 // We are using Reflection to add/remove internal events.
1938 // Class ListProvider uses the events.
1940 //Event used to generate UIA StructureChangedEvent
1941 static object UIACollectionChangedEvent = new object ();
1943 internal event CollectionChangeEventHandler UIACollectionChanged {
1944 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
1945 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
1948 internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
1950 CollectionChangeEventHandler eh
1951 = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
1957 #endregion UIA Framework Events
1959 public ObjectCollection (ComboBox owner)
1964 #region Public Properties
1966 get { return object_items.Count; }
1969 public bool IsReadOnly {
1970 get { return false; }
1974 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1975 public virtual object this [int index] {
1977 if (index < 0 || index >= Count)
1978 throw new ArgumentOutOfRangeException ("index");
1980 return object_items[index];
1983 if (index < 0 || index >= Count)
1984 throw new ArgumentOutOfRangeException ("index");
1986 throw new ArgumentNullException ("value");
1989 //UIA Framework event: Item Removed
1990 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, index));
1993 object_items[index] = value;
1996 //UIA Framework event: Item Added
1997 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2000 if (owner.listbox_ctrl != null)
2001 owner.listbox_ctrl.InvalidateItem (index);
2002 if (index == owner.SelectedIndex) {
2003 if (owner.textbox_ctrl == null)
2006 owner.textbox_ctrl.SelectedText = value.ToString ();
2011 bool ICollection.IsSynchronized {
2012 get { return false; }
2015 object ICollection.SyncRoot {
2016 get { return this; }
2019 bool IList.IsFixedSize {
2020 get { return false; }
2023 #endregion Public Properties
2025 #region Public Methods
2026 public int Add (object item)
2030 idx = AddItem (item);
2031 owner.UpdatedItems ();
2035 public void AddRange (object[] items)
2038 throw new ArgumentNullException ("items");
2040 foreach (object mi in items)
2043 owner.UpdatedItems ();
2046 public void Clear ()
2048 owner.selected_index = -1;
2049 object_items.Clear ();
2050 owner.UpdatedItems ();
2054 //UIA Framework event: Items list cleared
2055 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, -1));
2059 public bool Contains (object value)
2062 throw new ArgumentNullException ("value");
2064 return object_items.Contains (value);
2068 public void CopyTo (object [] destination, int arrayIndex)
2070 object_items.CopyTo (destination, arrayIndex);
2073 void ICollection.CopyTo (Array destination, int index)
2075 object_items.CopyTo (destination, index);
2078 public void CopyTo (object [] dest, int arrayIndex)
2080 object_items.CopyTo (dest, arrayIndex);
2083 void ICollection.CopyTo (Array dest, int index)
2085 object_items.CopyTo (dest, index);
2089 public IEnumerator GetEnumerator ()
2091 return object_items.GetEnumerator ();
2094 int IList.Add (object item)
2099 public int IndexOf (object value)
2102 throw new ArgumentNullException ("value");
2104 return object_items.IndexOf (value);
2107 public void Insert (int index, object item)
2109 if (index < 0 || index > Count)
2110 throw new ArgumentOutOfRangeException ("index");
2112 throw new ArgumentNullException ("item");
2114 owner.BeginUpdate ();
2119 object_items.Insert (index, item);
2121 //UIA Framework event: Item added
2122 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2126 owner.EndUpdate (); // Calls UpdatedItems
2129 public void Remove (object value)
2134 if (IndexOf (value) == owner.SelectedIndex)
2135 owner.SelectedIndex = -1;
2137 RemoveAt (IndexOf (value));
2140 public void RemoveAt (int index)
2142 if (index < 0 || index >= Count)
2143 throw new ArgumentOutOfRangeException ("index");
2145 if (index == owner.SelectedIndex)
2146 owner.SelectedIndex = -1;
2148 object_items.RemoveAt (index);
2149 owner.UpdatedItems ();
2152 //UIA Framework event: Item removed
2153 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, index));
2156 #endregion Public Methods
2158 #region Private Methods
2159 private int AddItem (object item)
2162 throw new ArgumentNullException ("item");
2166 foreach (object o in object_items) {
2167 if (String.Compare (item.ToString (), o.ToString ()) < 0) {
2168 object_items.Insert (index, item);
2170 // If we added the new item before the selectedindex
2171 // bump the selectedindex by one, behavior differs if
2172 // Handle has not been created.
2173 if (index <= owner.selected_index && owner.IsHandleCreated)
2174 owner.selected_index++;
2177 //UIA Framework event: Item added
2178 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2186 object_items.Add (item);
2189 //UIA Framework event: Item added
2190 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, object_items.Count - 1));
2193 return object_items.Count - 1;
2196 internal void AddRange (IList items)
2198 foreach (object mi in items)
2201 owner.UpdatedItems ();
2204 internal void Sort ()
2206 object_items.Sort ();
2209 #endregion Private Methods
2212 internal class ComboTextBox : TextBox {
2214 private ComboBox owner;
2216 public ComboTextBox (ComboBox owner)
2219 ShowSelection = false;
2220 HideSelection = false;
2223 internal void SetSelectable (bool selectable)
2225 SetStyle (ControlStyles.Selectable, selectable);
2228 internal void ActivateCaret (bool active)
2231 document.CaretHasFocus ();
2233 document.CaretLostFocus ();
2237 internal override void OnTextUpdate ()
2239 base.OnTextUpdate ();
2240 owner.OnTextUpdate (EventArgs.Empty);
2244 protected override void OnGotFocus (EventArgs e)
2246 owner.Select (false, true);
2249 protected override void OnLostFocus (EventArgs e)
2251 owner.Select (false, true);
2254 public override bool Focused {
2256 return owner.Focused;
2260 internal override bool ActivateOnShow { get { return false; } }
2263 internal class ComboListBox : Control
2265 private ComboBox owner;
2266 private VScrollBarLB vscrollbar_ctrl;
2267 private int top_item; /* First item that we show the in the current page */
2268 private int last_item; /* Last visible item */
2269 internal int page_size; /* Number of listbox items per page */
2270 private Rectangle textarea_drawable; /* Rectangle of the drawable text area */
2272 internal enum ItemNavigation
2282 class VScrollBarLB : VScrollBar
2284 public VScrollBarLB ()
2288 internal override bool InternalCapture {
2289 get { return Capture; }
2293 public void FireMouseDown (MouseEventArgs e)
2298 e = TranslateEvent (e);
2302 public void FireMouseUp (MouseEventArgs e)
2307 e = TranslateEvent (e);
2311 public void FireMouseMove (MouseEventArgs e)
2316 e = TranslateEvent (e);
2320 MouseEventArgs TranslateEvent (MouseEventArgs e)
2322 Point loc = PointToClient (Control.MousePosition);
2323 return new MouseEventArgs (e.Button, e.Clicks, loc.X, loc.Y, e.Delta);
2327 public ComboListBox (ComboBox owner)
2334 MouseWheel += new MouseEventHandler (OnMouseWheelCLB);
2336 SetStyle (ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
2337 SetStyle (ControlStyles.ResizeRedraw | ControlStyles.Opaque, true);
2339 this.is_visible = false;
2341 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2342 InternalBorderStyle = BorderStyle.Fixed3D;
2344 InternalBorderStyle = BorderStyle.FixedSingle;
2347 protected override CreateParams CreateParams
2350 CreateParams cp = base.CreateParams;
2351 if (owner == null || owner.DropDownStyle == ComboBoxStyle.Simple)
2354 cp.Style ^= (int)WindowStyles.WS_CHILD;
2355 cp.Style ^= (int)WindowStyles.WS_VISIBLE;
2356 cp.Style |= (int)WindowStyles.WS_POPUP;
2357 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW | (int) WindowExStyles.WS_EX_TOPMOST;
2362 internal override bool InternalCapture {
2371 internal override bool ActivateOnShow { get { return false; } }
2372 #region Private Methods
2374 // Calcs the listbox area
2375 internal void CalcListBoxArea ()
2378 bool show_scrollbar = false;
2380 if (owner.DropDownStyle == ComboBoxStyle.Simple) {
2381 Rectangle area = owner.listbox_area;
2383 height = area.Height;
2385 // No calculation needed
2386 if (height <= 0 || width <= 0)
2389 else { // DropDown or DropDownList
2391 width = owner.DropDownWidth;
2392 int count = (owner.Items.Count <= owner.MaxDropDownItems) ? owner.Items.Count : owner.MaxDropDownItems;
2394 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2396 for (int i = 0; i < count; i++) {
2397 height += owner.GetItemHeight (i);
2402 height = owner.DropDownHeight;
2404 height = owner.ItemHeight * count;
2409 page_size = Math.Max (height / owner.ItemHeight, 1);
2411 ComboBoxStyle dropdown_style = owner.DropDownStyle;
2412 if ((dropdown_style != ComboBoxStyle.Simple && owner.Items.Count <= owner.MaxDropDownItems)
2413 || (dropdown_style == ComboBoxStyle.Simple && owner.Items.Count * owner.ItemHeight < height)) {
2415 if (vscrollbar_ctrl != null)
2416 vscrollbar_ctrl.Visible = false;
2417 if (dropdown_style != ComboBoxStyle.Simple)
2418 height = owner.ItemHeight * owner.items.Count;
2420 /* Need vertical scrollbar */
2421 if (vscrollbar_ctrl == null) {
2422 vscrollbar_ctrl = new VScrollBarLB ();
2423 vscrollbar_ctrl.Minimum = 0;
2424 vscrollbar_ctrl.SmallChange = 1;
2425 vscrollbar_ctrl.LargeChange = 1;
2426 vscrollbar_ctrl.Maximum = 0;
2427 vscrollbar_ctrl.ValueChanged += new EventHandler (VerticalScrollEvent);
2428 Controls.AddImplicit (vscrollbar_ctrl);
2431 vscrollbar_ctrl.Dock = DockStyle.Right;
2433 vscrollbar_ctrl.Maximum = owner.Items.Count - 1;
2435 int large = page_size;
2437 int large = (dropdown_style == ComboBoxStyle.Simple ? page_size : owner.maxdrop_items) - 1;
2441 vscrollbar_ctrl.LargeChange = large;
2442 show_scrollbar = vscrollbar_ctrl.Visible = true;
2444 int hli = HighlightedIndex;
2446 hli = Math.Min (hli, vscrollbar_ctrl.Maximum);
2447 vscrollbar_ctrl.Value = hli;
2451 Size = new Size (width, height);
2452 textarea_drawable = ClientRectangle;
2453 textarea_drawable.Width = width;
2454 textarea_drawable.Height = height;
2456 if (vscrollbar_ctrl != null && show_scrollbar)
2457 textarea_drawable.Width -= vscrollbar_ctrl.Width;
2459 last_item = LastVisibleItem ();
2462 private void Draw (Rectangle clip, Graphics dc)
2464 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (owner.BackColor), clip);
2466 if (owner.Items.Count > 0) {
2468 for (int i = top_item; i <= last_item; i++) {
2469 Rectangle item_rect = GetItemDisplayRectangle (i, top_item);
2471 if (!clip.IntersectsWith (item_rect))
2474 DrawItemState state = DrawItemState.None;
2476 if (i == HighlightedIndex) {
2477 state |= DrawItemState.Selected;
2479 if (owner.DropDownStyle == ComboBoxStyle.DropDownList) {
2480 state |= DrawItemState.Focus;
2484 owner.OnDrawItem (new DrawItemEventArgs (dc, owner.Font, item_rect,
2485 i, state, owner.ForeColor, owner.BackColor));
2490 int highlighted_index = -1;
2492 public int HighlightedIndex {
2493 get { return highlighted_index; }
2495 if (highlighted_index == value)
2498 if (highlighted_index != -1 && highlighted_index < this.owner.Items.Count)
2499 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2500 highlighted_index = value;
2501 if (highlighted_index != -1)
2502 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2506 private Rectangle GetItemDisplayRectangle (int index, int top_index)
2508 if (index < 0 || index >= owner.Items.Count)
2509 throw new ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
2511 Rectangle item_rect = new Rectangle ();
2512 int height = owner.GetItemHeight (index);
2515 item_rect.Width = textarea_drawable.Width;
2516 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2518 for (int i = top_index; i < index; i++)
2519 item_rect.Y += owner.GetItemHeight (i);
2521 item_rect.Y = height * (index - top_index);
2523 item_rect.Height = height;
2527 public void HideWindow ()
2529 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2534 owner.DropDownListBoxFinished ();
2537 private int IndexFromPointDisplayRectangle (int x, int y)
2539 for (int i = top_item; i <= last_item; i++) {
2540 if (GetItemDisplayRectangle (i, top_item).Contains (x, y) == true)
2547 public void InvalidateItem (int index)
2550 Invalidate (GetItemDisplayRectangle (index, top_item));
2553 public int LastVisibleItem ()
2555 Rectangle item_rect;
2556 int top_y = textarea_drawable.Y + textarea_drawable.Height;
2559 for (i = top_item; i < owner.Items.Count; i++) {
2560 item_rect = GetItemDisplayRectangle (i, top_item);
2561 if (item_rect.Y + item_rect.Height > top_y) {
2568 public void SetTopItem (int item)
2570 if (top_item == item)
2573 UpdateLastVisibleItem ();
2577 public int FirstVisibleItem ()
2582 bool scrollbar_grabbed = false;
2586 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.is_visible)
2589 return vscrollbar_ctrl.Bounds.Contains (PointToClient (Control.MousePosition));
2593 protected override void OnMouseDown (MouseEventArgs e)
2596 vscrollbar_ctrl.FireMouseDown (e);
2597 scrollbar_grabbed = true;
2601 protected override void OnMouseMove (MouseEventArgs e)
2603 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2606 if (scrollbar_grabbed || (!Capture && InScrollBar)) {
2607 vscrollbar_ctrl.FireMouseMove (e);
2611 Point pt = PointToClient (Control.MousePosition);
2612 int index = IndexFromPointDisplayRectangle (pt.X, pt.Y);
2615 HighlightedIndex = index;
2618 protected override void OnMouseUp (MouseEventArgs e)
2620 int index = IndexFromPointDisplayRectangle (e.X, e.Y);
2622 if (scrollbar_grabbed) {
2623 vscrollbar_ctrl.FireMouseUp (e);
2624 scrollbar_grabbed = false;
2626 HighlightedIndex = index;
2635 owner.SelectedIndex = index;
2636 owner.OnSelectionChangeCommitted (new EventArgs ());
2640 internal override void OnPaintInternal (PaintEventArgs pevent)
2642 Draw (pevent.ClipRectangle,pevent.Graphics);
2645 public bool ShowWindow ()
2647 if (owner.DropDownStyle == ComboBoxStyle.Simple && owner.Items.Count == 0)
2650 HighlightedIndex = owner.SelectedIndex;
2656 owner.OnDropDown (EventArgs.Empty);
2660 public void UpdateLastVisibleItem ()
2662 last_item = LastVisibleItem ();
2665 public void Scroll (int delta)
2667 if (delta == 0 || vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2670 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2672 int val = vscrollbar_ctrl.Value + delta;
2675 else if (val < vscrollbar_ctrl.Minimum)
2676 val = vscrollbar_ctrl.Minimum;
2677 vscrollbar_ctrl.Value = val;
2680 private void OnMouseWheelCLB (object sender, MouseEventArgs me)
2682 if (owner.Items.Count == 0)
2685 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
2690 private void VerticalScrollEvent (object sender, EventArgs e)
2692 if (top_item == vscrollbar_ctrl.Value)
2695 top_item = vscrollbar_ctrl.Value;
2696 UpdateLastVisibleItem ();
2700 protected override void WndProc(ref Message m) {
2701 if (m.Msg == (int)Msg.WM_SETFOCUS) {
2702 owner.Select (false, true);
2704 base.WndProc (ref m);
2707 #endregion Private Methods