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 process_texchanged_autoscroll = true;
63 private bool item_height_specified;
64 private int item_height;
65 private int requested_height = -1;
66 private Hashtable item_heights;
67 private bool show_dropdown_button;
68 private ButtonState button_state = ButtonState.Normal;
69 private bool dropped_down;
70 private Rectangle text_area;
71 private Rectangle button_area;
72 private Rectangle listbox_area;
73 private const int button_width = 16;
74 bool drop_down_button_entered;
76 private AutoCompleteStringCollection auto_complete_custom_source = null;
77 private AutoCompleteMode auto_complete_mode = AutoCompleteMode.None;
78 private AutoCompleteSource auto_complete_source = AutoCompleteSource.None;
79 private FlatStyle flat_style;
80 private int drop_down_height;
81 const int default_drop_down_height = 106;
85 public class ChildAccessibleObject : AccessibleObject {
87 public ChildAccessibleObject (ComboBox owner, IntPtr handle)
92 public override string Name {
101 items = new ObjectCollection (this);
102 DropDownStyle = ComboBoxStyle.DropDown;
103 item_height = FontHeight + 2;
104 background_color = ThemeEngine.Current.ColorWindow;
105 border_style = BorderStyle.None;
108 drop_down_height = default_drop_down_height;
109 flat_style = FlatStyle.Standard;
113 MouseDown += new MouseEventHandler (OnMouseDownCB);
114 MouseUp += new MouseEventHandler (OnMouseUpCB);
115 MouseMove += new MouseEventHandler (OnMouseMoveCB);
116 MouseWheel += new MouseEventHandler (OnMouseWheelCB);
117 MouseEnter += new EventHandler (OnMouseEnter);
118 MouseLeave += new EventHandler (OnMouseLeave);
119 KeyDown +=new KeyEventHandler(OnKeyDownCB);
125 [EditorBrowsable (EditorBrowsableState.Never)]
126 public new event EventHandler BackgroundImageChanged {
127 add { base.BackgroundImageChanged += value; }
128 remove { base.BackgroundImageChanged -= value; }
134 [EditorBrowsable (EditorBrowsableState.Never)]
135 public new event EventHandler BackgroundImageLayoutChanged
137 add { base.BackgroundImageLayoutChanged += value; }
138 remove { base.BackgroundImageLayoutChanged -= value; }
142 [EditorBrowsable (EditorBrowsableState.Never)]
143 public new event EventHandler DoubleClick
145 add { base.DoubleClick += value; }
146 remove { base.DoubleClick -= value; }
150 static object DrawItemEvent = new object ();
151 static object DropDownEvent = new object ();
152 static object DropDownStyleChangedEvent = new object ();
153 static object MeasureItemEvent = new object ();
154 static object SelectedIndexChangedEvent = new object ();
155 static object SelectionChangeCommittedEvent = new object ();
157 static object DropDownClosedEvent = new object ();
158 static object TextUpdateEvent = new object ();
161 public event DrawItemEventHandler DrawItem {
162 add { Events.AddHandler (DrawItemEvent, value); }
163 remove { Events.RemoveHandler (DrawItemEvent, value); }
166 public event EventHandler DropDown {
167 add { Events.AddHandler (DropDownEvent, value); }
168 remove { Events.RemoveHandler (DropDownEvent, value); }
171 public event EventHandler DropDownClosed
173 add { Events.AddHandler (DropDownClosedEvent, value); }
174 remove { Events.RemoveHandler (DropDownClosedEvent, value); }
178 public event EventHandler DropDownStyleChanged {
179 add { Events.AddHandler (DropDownStyleChangedEvent, value); }
180 remove { Events.RemoveHandler (DropDownStyleChangedEvent, value); }
183 public event MeasureItemEventHandler MeasureItem {
184 add { Events.AddHandler (MeasureItemEvent, value); }
185 remove { Events.RemoveHandler (MeasureItemEvent, value); }
189 [EditorBrowsable (EditorBrowsableState.Never)]
190 public new event EventHandler PaddingChanged
192 add { base.PaddingChanged += value; }
193 remove { base.PaddingChanged -= value; }
198 [EditorBrowsable (EditorBrowsableState.Never)]
199 public new event PaintEventHandler Paint {
200 add { base.Paint += value; }
201 remove { base.Paint -= value; }
204 public event EventHandler SelectedIndexChanged {
205 add { Events.AddHandler (SelectedIndexChangedEvent, value); }
206 remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
209 public event EventHandler SelectionChangeCommitted {
210 add { Events.AddHandler (SelectionChangeCommittedEvent, value); }
211 remove { Events.RemoveHandler (SelectionChangeCommittedEvent, value); }
214 public event EventHandler TextUpdate
216 add { Events.AddHandler (TextUpdateEvent, value); }
217 remove { Events.RemoveHandler (TextUpdateEvent, value); }
223 #region Public Properties
225 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
226 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
228 [EditorBrowsable (EditorBrowsableState.Always)]
230 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design,
231 "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
232 public AutoCompleteStringCollection AutoCompleteCustomSource {
234 if(auto_complete_custom_source == null) {
235 auto_complete_custom_source = new AutoCompleteStringCollection ();
236 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
238 return auto_complete_custom_source;
241 if(auto_complete_custom_source == value)
244 if(auto_complete_custom_source != null) //remove eventhandler from old collection
245 auto_complete_custom_source.CollectionChanged -= new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
247 auto_complete_custom_source = value;
249 if(auto_complete_custom_source != null)
250 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
252 SetTextBoxAutoCompleteData ();
256 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
258 [EditorBrowsable (EditorBrowsableState.Always)]
259 [DefaultValue (AutoCompleteMode.None)]
260 public AutoCompleteMode AutoCompleteMode {
261 get { return auto_complete_mode; }
263 if(auto_complete_mode == value)
266 if((value < AutoCompleteMode.None) || (value > AutoCompleteMode.SuggestAppend))
267 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteMode", value));
269 auto_complete_mode = value;
270 SetTextBoxAutoCompleteData ();
274 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
276 [EditorBrowsable (EditorBrowsableState.Always)]
277 [DefaultValue (AutoCompleteSource.None)]
278 public AutoCompleteSource AutoCompleteSource {
279 get { return auto_complete_source; }
281 if(auto_complete_source == value)
284 if(!Enum.IsDefined (typeof (AutoCompleteSource), value))
285 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteSource", value));
287 auto_complete_source = value;
288 SetTextBoxAutoCompleteData ();
292 void SetTextBoxAutoCompleteData ()
294 if (textbox_ctrl == null)
297 textbox_ctrl.AutoCompleteMode = auto_complete_mode;
299 if (auto_complete_source == AutoCompleteSource.ListItems) {
300 textbox_ctrl.AutoCompleteSource = AutoCompleteSource.CustomSource;
301 textbox_ctrl.AutoCompleteCustomSource = null;
302 textbox_ctrl.AutoCompleteInternalSource = this;
304 textbox_ctrl.AutoCompleteSource = auto_complete_source;
305 textbox_ctrl.AutoCompleteCustomSource = auto_complete_custom_source;
306 textbox_ctrl.AutoCompleteInternalSource = null;
310 public override Color BackColor {
311 get { return base.BackColor; }
313 if (base.BackColor == value)
315 base.BackColor = value;
321 [EditorBrowsable (EditorBrowsableState.Never)]
322 public override Image BackgroundImage {
323 get { return base.BackgroundImage; }
325 if (base.BackgroundImage == value)
327 base.BackgroundImage = value;
334 [EditorBrowsable (EditorBrowsableState.Never)]
335 public override ImageLayout BackgroundImageLayout {
336 get { return base.BackgroundImageLayout; }
337 set { base.BackgroundImageLayout = value; }
341 protected override CreateParams CreateParams {
342 get { return base.CreateParams;}
346 [DefaultValue ((string)null)]
347 [AttributeProvider (typeof (IListSource))]
348 [RefreshProperties (RefreshProperties.Repaint)]
349 [MWFCategory("Data")]
350 public new object DataSource {
351 get { return base.DataSource; }
352 set { base.DataSource = value; }
356 protected override Size DefaultSize {
357 get { return new Size (121, 21); }
360 [RefreshProperties(RefreshProperties.Repaint)]
361 [DefaultValue (DrawMode.Normal)]
362 [MWFCategory("Behavior")]
363 public DrawMode DrawMode {
364 get { return draw_mode; }
366 if (!Enum.IsDefined (typeof (DrawMode), value))
367 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for DrawMode", value));
369 if (draw_mode == value)
372 if (draw_mode == DrawMode.OwnerDrawVariable)
375 if (draw_mode == DrawMode.OwnerDrawVariable)
376 item_heights = new Hashtable ();
384 [EditorBrowsable (EditorBrowsableState.Always)]
385 [MWFCategory("Behavior")]
386 public int DropDownHeight {
388 return drop_down_height;
392 throw new ArgumentOutOfRangeException ("DropDownHeight", "DropDownHeight must be greater than 0.");
394 if (value == drop_down_height)
397 drop_down_height = value;
398 IntegralHeight = false;
403 [DefaultValue (ComboBoxStyle.DropDown)]
404 [RefreshProperties(RefreshProperties.Repaint)]
405 [MWFCategory("Appearance")]
406 public ComboBoxStyle DropDownStyle {
407 get { return dropdown_style; }
409 if (!Enum.IsDefined (typeof (ComboBoxStyle), value))
410 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for ComboBoxStyle", value));
412 if (dropdown_style == value)
417 if (dropdown_style == ComboBoxStyle.Simple) {
418 if (listbox_ctrl != null) {
419 Controls.RemoveImplicit (listbox_ctrl);
420 listbox_ctrl.Dispose ();
425 dropdown_style = value;
427 if (dropdown_style == ComboBoxStyle.DropDownList && textbox_ctrl != null) {
428 Controls.RemoveImplicit (textbox_ctrl);
429 textbox_ctrl.Dispose ();
433 if (dropdown_style == ComboBoxStyle.Simple) {
434 show_dropdown_button = false;
436 CreateComboListBox ();
437 Controls.AddImplicit (listbox_ctrl);
438 listbox_ctrl.Visible = true;
440 // This should give us a 150 default height
441 // for Simple mode if size hasn't been set
442 // (DefaultSize doesn't work for us in this case)
443 if (requested_height == -1)
444 requested_height = 150;
446 show_dropdown_button = true;
447 button_state = ButtonState.Normal;
450 if (dropdown_style != ComboBoxStyle.DropDownList && textbox_ctrl == null) {
451 textbox_ctrl = new ComboTextBox (this);
452 object selected_item = SelectedItem;
453 if (selected_item != null)
454 textbox_ctrl.Text = GetItemText (selected_item);
455 textbox_ctrl.BorderStyle = BorderStyle.None;
456 textbox_ctrl.TextChanged += new EventHandler (OnTextChangedEdit);
457 textbox_ctrl.KeyPress += new KeyPressEventHandler (OnTextKeyPress);
458 textbox_ctrl.Click += new EventHandler (OnTextBoxClick);
459 textbox_ctrl.ContextMenu = ContextMenu;
461 if (IsHandleCreated == true)
462 Controls.AddImplicit (textbox_ctrl);
464 SetTextBoxAutoCompleteData ();
469 OnDropDownStyleChanged (EventArgs.Empty);
472 UpdateComboBoxBounds ();
477 [MWFCategory("Behavior")]
478 public int DropDownWidth {
480 if (dropdown_width == -1)
483 return dropdown_width;
486 if (dropdown_width == value)
491 throw new ArgumentOutOfRangeException ("DropDownWidth",
492 "The DropDownWidth value is less than one.");
494 throw new ArgumentException ("The DropDownWidth value is less than one.");
497 dropdown_width = value;
502 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
503 public bool DroppedDown {
505 if (dropdown_style == ComboBoxStyle.Simple)
511 if (dropdown_style == ComboBoxStyle.Simple || dropped_down == value)
517 listbox_ctrl.HideWindow ();
522 [DefaultValue (FlatStyle.Standard)]
524 [MWFCategory("Appearance")]
525 public FlatStyle FlatStyle {
526 get { return flat_style; }
528 if (!Enum.IsDefined (typeof (FlatStyle), value))
529 throw new InvalidEnumArgumentException ("FlatStyle", (int) value, typeof (FlatStyle));
538 public override bool Focused {
539 get { return base.Focused; }
542 public override Color ForeColor {
543 get { return base.ForeColor; }
545 if (base.ForeColor == value)
547 base.ForeColor = value;
552 [DefaultValue (true)]
554 [MWFCategory("Behavior")]
555 public bool IntegralHeight {
556 get { return integral_height; }
558 if (integral_height == value)
560 integral_height = value;
561 UpdateComboBoxBounds ();
567 [MWFCategory("Behavior")]
568 public int ItemHeight {
570 if (item_height == -1) {
571 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
572 item_height = (int) sz.Height;
579 throw new ArgumentOutOfRangeException ("ItemHeight",
580 "The item height value is less than one.");
582 throw new ArgumentException ("The item height value is less than one.");
585 item_height_specified = true;
588 UpdateComboBoxBounds ();
594 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
596 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
598 [MergableProperty (false)]
600 [MWFCategory("Data")]
601 public ComboBox.ObjectCollection Items {
602 get { return items; }
607 [MWFCategory("Behavior")]
608 public int MaxDropDownItems {
609 get { return maxdrop_items; }
611 if (maxdrop_items == value)
613 maxdrop_items = value;
618 public override Size MaximumSize {
619 get { return base.MaximumSize; }
621 base.MaximumSize = new Size (value.Width, 0);
628 [MWFCategory("Behavior")]
629 public int MaxLength {
630 get { return max_length; }
632 if (max_length == value)
637 if (dropdown_style != ComboBoxStyle.DropDownList) {
641 textbox_ctrl.MaxLength = value;
647 public override Size MinimumSize {
648 get { return base.MinimumSize; }
650 base.MinimumSize = new Size (value.Width, 0);
654 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
655 [EditorBrowsable (EditorBrowsableState.Never)]
657 public new Padding Padding {
658 get { return base.Padding; }
659 set { base.Padding = value; }
663 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
665 public int PreferredHeight {
666 get { return Font.Height + 8; }
670 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
671 public override int SelectedIndex {
672 get { return selected_index; }
674 SetSelectedIndex (value, false);
679 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
681 public object SelectedItem {
682 get { return selected_index == -1 ? null : Items [selected_index]; }
684 object item = selected_index == -1 ? null : Items [selected_index];
691 SelectedIndex = Items.IndexOf (value);
696 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
697 public string SelectedText {
699 if (dropdown_style == ComboBoxStyle.DropDownList)
702 string retval = textbox_ctrl.SelectedText;
705 // On 1.1, the textbox will return null, combobox returns ""
706 if (retval == null && !textbox_ctrl.IsHandleCreated)
712 if (dropdown_style == ComboBoxStyle.DropDownList)
714 textbox_ctrl.SelectedText = value;
719 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
720 public int SelectionLength {
722 if (dropdown_style == ComboBoxStyle.DropDownList)
725 int result = textbox_ctrl.SelectionLength;
726 return result == -1 ? 0 : result;
729 if (dropdown_style == ComboBoxStyle.DropDownList)
731 if (textbox_ctrl.SelectionLength == value)
733 textbox_ctrl.SelectionLength = value;
738 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
739 public int SelectionStart {
741 if (dropdown_style == ComboBoxStyle.DropDownList)
743 return textbox_ctrl.SelectionStart;
746 if (dropdown_style == ComboBoxStyle.DropDownList)
748 if (textbox_ctrl.SelectionStart == value)
750 textbox_ctrl.SelectionStart = value;
754 [DefaultValue (false)]
755 [MWFCategory("Behavior")]
757 get { return sorted; }
772 public override string Text {
774 if (dropdown_style != ComboBoxStyle.DropDownList) {
775 if (textbox_ctrl != null) {
776 return textbox_ctrl.Text;
780 if (SelectedItem != null)
781 return GetItemText (SelectedItem);
787 if (SelectedIndex == -1) {
788 if (dropdown_style != ComboBoxStyle.DropDownList)
789 SetControlText (string.Empty, false);
796 // do nothing if value exactly matches text of selected item
797 if (SelectedItem != null && string.Compare (value, GetItemText (SelectedItem), false, CultureInfo.CurrentCulture) == 0)
800 // find exact match using case-sensitive comparison, and if does
801 // not result in any match then use case-insensitive comparison
802 int index = FindStringExact (value, -1, false);
804 index = FindStringExact (value, -1, true);
807 SelectedIndex = index;
811 if (dropdown_style != ComboBoxStyle.DropDownList)
812 textbox_ctrl.Text = GetItemText (value);
816 #endregion Public Properties
818 #region Internal Properties
819 internal Rectangle ButtonArea {
820 get { return button_area; }
823 internal Rectangle TextArea {
824 get { return text_area; }
828 #region UIA Framework Properties
830 internal TextBox UIATextBox {
831 get { return textbox_ctrl; }
834 internal ComboListBox UIAComboListBox {
835 get { return listbox_ctrl; }
838 #endregion UIA Framework Properties
840 #region Public Methods
842 [Obsolete ("This method has been deprecated")]
844 protected virtual void AddItemsCore (object[] value)
849 public void BeginUpdate ()
851 suspend_ctrlupdate = true;
855 protected override AccessibleObject CreateAccessibilityInstance ()
857 return base.CreateAccessibilityInstance ();
860 protected override void CreateHandle ()
862 base.CreateHandle ();
866 protected override void Dispose (bool disposing)
869 if (listbox_ctrl != null) {
870 listbox_ctrl.Dispose ();
871 Controls.RemoveImplicit (listbox_ctrl);
875 if (textbox_ctrl != null) {
876 Controls.RemoveImplicit (textbox_ctrl);
877 textbox_ctrl.Dispose ();
882 base.Dispose (disposing);
885 public void EndUpdate ()
887 suspend_ctrlupdate = false;
892 public int FindString (string s)
894 return FindString (s, -1);
897 public int FindString (string s, int startIndex)
899 if (s == null || Items.Count == 0)
903 if (startIndex < -1 || startIndex >= Items.Count)
905 if (startIndex < -1 || startIndex >= Items.Count - 1)
907 throw new ArgumentOutOfRangeException ("startIndex");
911 if (i == (Items.Count - 1))
916 if (string.Compare (s, 0, GetItemText (Items [i]), 0, s.Length, true) == 0)
918 if (i == (Items.Count - 1))
920 } while (i != startIndex);
925 public int FindStringExact (string s)
927 return FindStringExact (s, -1);
930 public int FindStringExact (string s, int startIndex)
932 return FindStringExact (s, startIndex, true);
935 private int FindStringExact (string s, int startIndex, bool ignoreCase)
937 if (s == null || Items.Count == 0)
941 if (startIndex < -1 || startIndex >= Items.Count)
943 if (startIndex < -1 || startIndex >= Items.Count - 1)
945 throw new ArgumentOutOfRangeException ("startIndex");
949 if (i == (Items.Count - 1))
954 if (string.Compare (s, GetItemText (Items [i]), ignoreCase, CultureInfo.CurrentCulture) == 0)
956 if (i == (Items.Count - 1))
958 } while (i != startIndex);
963 public int GetItemHeight (int index)
965 if (DrawMode == DrawMode.OwnerDrawVariable && IsHandleCreated) {
967 if (index < 0 || index >= Items.Count )
968 throw new ArgumentOutOfRangeException ("The item height value is less than zero");
970 object item = Items [index];
971 if (item_heights.Contains (item))
972 return (int) item_heights [item];
974 MeasureItemEventArgs args = new MeasureItemEventArgs (DeviceContext, index, ItemHeight);
975 OnMeasureItem (args);
976 item_heights [item] = args.ItemHeight;
977 return args.ItemHeight;
983 protected override bool IsInputKey (Keys keyData)
985 switch (keyData & ~Keys.Modifiers) {
1001 protected override void OnBackColorChanged (EventArgs e)
1003 base.OnBackColorChanged (e);
1005 if (textbox_ctrl != null)
1006 textbox_ctrl.BackColor = BackColor;
1009 protected override void OnDataSourceChanged (EventArgs e)
1011 base.OnDataSourceChanged (e);
1014 if (DataSource == null || DataManager == null) {
1018 SelectedIndex = DataManager.Position;
1022 protected override void OnDisplayMemberChanged (EventArgs e)
1024 base.OnDisplayMemberChanged (e);
1026 if (DataManager == null)
1029 SelectedIndex = DataManager.Position;
1031 if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1032 SetControlText (GetItemText (Items [selected_index]), true);
1034 if (!IsHandleCreated)
1040 protected virtual void OnDrawItem (DrawItemEventArgs e)
1042 DrawItemEventHandler eh = (DrawItemEventHandler)(Events [DrawItemEvent]);
1047 internal void HandleDrawItem (DrawItemEventArgs e)
1049 // Only raise OnDrawItem if we are in an OwnerDraw mode
1051 case DrawMode.OwnerDrawFixed:
1052 case DrawMode.OwnerDrawVariable:
1056 ThemeEngine.Current.DrawComboBoxItem (this, e);
1061 protected virtual void OnDropDown (EventArgs e)
1063 EventHandler eh = (EventHandler)(Events [DropDownEvent]);
1069 protected virtual void OnDropDownClosed (EventArgs e)
1071 EventHandler eh = (EventHandler) Events [DropDownClosedEvent];
1077 protected virtual void OnDropDownStyleChanged (EventArgs e)
1079 EventHandler eh = (EventHandler)(Events [DropDownStyleChangedEvent]);
1084 protected override void OnFontChanged (EventArgs e)
1086 base.OnFontChanged (e);
1088 if (textbox_ctrl != null)
1089 textbox_ctrl.Font = Font;
1091 if (!item_height_specified)
1092 item_height = Font.Height + 2;
1095 UpdateComboBoxBounds ();
1100 protected override void OnForeColorChanged (EventArgs e)
1102 base.OnForeColorChanged (e);
1103 if (textbox_ctrl != null)
1104 textbox_ctrl.ForeColor = ForeColor;
1107 [EditorBrowsable(EditorBrowsableState.Advanced)]
1108 protected override void OnGotFocus (EventArgs e)
1110 if (dropdown_style == ComboBoxStyle.DropDownList) {
1111 // We draw DDL styles manually, so they require a
1112 // refresh to have their selection drawn
1116 if (textbox_ctrl != null) {
1117 textbox_ctrl.SetSelectable (false);
1118 textbox_ctrl.ShowSelection = true;
1119 textbox_ctrl.ActivateCaret (true);
1120 textbox_ctrl.SelectAll ();
1123 base.OnGotFocus (e);
1126 [EditorBrowsable(EditorBrowsableState.Advanced)]
1127 protected override void OnLostFocus (EventArgs e)
1129 if (dropdown_style == ComboBoxStyle.DropDownList) {
1130 // We draw DDL styles manually, so they require a
1131 // refresh to have their selection drawn
1135 if (listbox_ctrl != null && dropped_down) {
1136 listbox_ctrl.HideWindow ();
1139 if (textbox_ctrl != null) {
1140 textbox_ctrl.SetSelectable (true);
1141 textbox_ctrl.ActivateCaret (false);
1142 textbox_ctrl.ShowSelection = false;
1143 textbox_ctrl.SelectionLength = 0;
1145 textbox_ctrl.HideAutoCompleteList ();
1149 base.OnLostFocus (e);
1152 protected override void OnHandleCreated (EventArgs e)
1154 base.OnHandleCreated (e);
1156 SetBoundsInternal (Left, Top, Width, PreferredHeight, BoundsSpecified.None);
1158 if (textbox_ctrl != null)
1159 Controls.AddImplicit (textbox_ctrl);
1162 UpdateComboBoxBounds ();
1165 protected override void OnHandleDestroyed (EventArgs e)
1167 base.OnHandleDestroyed (e);
1170 protected override void OnKeyPress (KeyPressEventArgs e)
1172 if (dropdown_style == ComboBoxStyle.DropDownList) {
1173 int index = FindStringCaseInsensitive (e.KeyChar.ToString (), SelectedIndex + 1);
1175 SelectedIndex = index;
1176 if (DroppedDown) { //Scroll into view
1177 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1178 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1179 // Or, selecting an item earlier in the list.
1180 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1181 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1186 base.OnKeyPress (e);
1189 protected virtual void OnMeasureItem (MeasureItemEventArgs e)
1191 MeasureItemEventHandler eh = (MeasureItemEventHandler)(Events [MeasureItemEvent]);
1196 protected override void OnParentBackColorChanged (EventArgs e)
1198 base.OnParentBackColorChanged (e);
1201 protected override void OnResize (EventArgs e)
1204 if (listbox_ctrl != null)
1205 listbox_ctrl.CalcListBoxArea ();
1208 protected override void OnSelectedIndexChanged (EventArgs e)
1210 base.OnSelectedIndexChanged (e);
1212 EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
1217 protected virtual void OnSelectedItemChanged (EventArgs e)
1221 protected override void OnSelectedValueChanged (EventArgs e)
1223 base.OnSelectedValueChanged (e);
1226 protected virtual void OnSelectionChangeCommitted (EventArgs e)
1228 EventHandler eh = (EventHandler)(Events [SelectionChangeCommittedEvent]);
1233 protected override void RefreshItem (int index)
1235 if (index < 0 || index >= Items.Count)
1236 throw new ArgumentOutOfRangeException ("index");
1238 if (draw_mode == DrawMode.OwnerDrawVariable)
1239 item_heights.Remove (Items [index]);
1243 protected override void RefreshItems ()
1245 for (int i = 0; i < Items.Count; i++) {
1252 if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1253 SetControlText (GetItemText (Items [selected_index]), false);
1256 public override void ResetText ()
1258 Text = String.Empty;
1261 protected override bool ProcessKeyEventArgs (ref Message m)
1263 return base.ProcessKeyEventArgs (ref m);
1266 [EditorBrowsable (EditorBrowsableState.Advanced)]
1267 protected override void OnKeyDown (KeyEventArgs e)
1272 [EditorBrowsable (EditorBrowsableState.Advanced)]
1273 protected override void OnValidating (CancelEventArgs e)
1275 base.OnValidating (e);
1278 [EditorBrowsable (EditorBrowsableState.Advanced)]
1279 protected override void OnTextChanged (EventArgs e)
1281 base.OnTextChanged (e);
1285 protected virtual void OnTextUpdate (EventArgs e)
1287 EventHandler eh = (EventHandler) Events [TextUpdateEvent];
1292 protected override void OnMouseLeave (EventArgs e)
1295 if (flat_style == FlatStyle.Popup)
1298 base.OnMouseLeave (e);
1301 protected override void OnMouseEnter (EventArgs e)
1304 if (flat_style == FlatStyle.Popup)
1307 base.OnMouseEnter (e);
1312 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
1314 base.ScaleControl (factor, specified);
1318 public void Select (int start, int length)
1321 throw new ArgumentException ("Start cannot be less than zero");
1324 throw new ArgumentException ("length cannot be less than zero");
1326 if (dropdown_style == ComboBoxStyle.DropDownList)
1329 textbox_ctrl.Select (start, length);
1332 public void SelectAll ()
1334 if (dropdown_style == ComboBoxStyle.DropDownList)
1337 if (textbox_ctrl != null) {
1338 textbox_ctrl.ShowSelection = true;
1339 textbox_ctrl.SelectAll ();
1343 protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified)
1345 bool vertically_anchored = (Anchor & AnchorStyles.Top) != 0 && (Anchor & AnchorStyles.Bottom) != 0;
1346 bool vertically_docked = Dock == DockStyle.Left || Dock == DockStyle.Right || Dock == DockStyle.Fill;
1348 if ((specified & BoundsSpecified.Height) != 0 ||
1349 (specified == BoundsSpecified.None && (vertically_anchored || vertically_docked))) {
1351 requested_height = height;
1352 height = SnapHeight (height);
1355 base.SetBoundsCore (x, y, width, height, specified);
1358 protected override void SetItemCore (int index, object value)
1360 if (index < 0 || index >= Items.Count)
1363 Items[index] = value;
1366 protected override void SetItemsCore (IList value)
1371 Items.AddRange (value);
1377 public override string ToString ()
1379 return base.ToString () + ", Items.Count:" + Items.Count;
1382 protected override void WndProc (ref Message m)
1384 switch ((Msg) m.Msg) {
1386 case Msg.WM_KEYDOWN:
1387 Keys keys = (Keys) m.WParam.ToInt32 ();
1389 // Don't pass the message to base if auto complete is being used and available.
1390 if (textbox_ctrl != null && textbox_ctrl.CanNavigateAutoCompleteList) {
1391 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1395 if (keys == Keys.Up || keys == Keys.Down)
1397 goto case Msg.WM_CHAR;
1399 if (textbox_ctrl != null)
1400 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1402 case Msg.WM_MOUSELEAVE:
1403 Point location = PointToClient (Control.MousePosition);
1404 if (ClientRectangle.Contains (location))
1410 base.WndProc (ref m);
1413 #endregion Public Methods
1415 #region Private Methods
1417 void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) {
1418 if(auto_complete_source == AutoCompleteSource.CustomSource) {
1419 //FIXME: handle add, remove and refresh events in AutoComplete algorithm.
1424 internal override bool InternalCapture {
1425 get { return Capture; }
1429 void LayoutComboBox ()
1431 int border = ThemeEngine.Current.Border3DSize.Width;
1433 text_area = ClientRectangle;
1434 text_area.Height = PreferredHeight;
1436 listbox_area = ClientRectangle;
1437 listbox_area.Y = text_area.Bottom + 3;
1438 listbox_area.Height -= (text_area.Height + 2);
1440 Rectangle prev_button_area = button_area;
1442 if (DropDownStyle == ComboBoxStyle.Simple)
1443 button_area = Rectangle.Empty;
1445 button_area = text_area;
1446 button_area.X = text_area.Right - button_width - border;
1447 button_area.Y = text_area.Y + border;
1448 button_area.Width = button_width;
1449 button_area.Height = text_area.Height - 2 * border;
1451 if (flat_style == FlatStyle.Popup || flat_style == FlatStyle.Flat) {
1452 button_area.Inflate (1, 1);
1454 button_area.Width -= 2;
1459 if (button_area != prev_button_area) {
1460 prev_button_area.Y -= border;
1461 prev_button_area.Width += border;
1462 prev_button_area.Height += 2 * border;
1463 Invalidate (prev_button_area);
1464 Invalidate (button_area);
1467 if (textbox_ctrl != null) {
1468 int text_border = border + 1;
1469 textbox_ctrl.Location = new Point (text_area.X + text_border, text_area.Y + text_border);
1470 textbox_ctrl.Width = text_area.Width - button_area.Width - text_border * 2;
1471 textbox_ctrl.Height = text_area.Height - text_border * 2;
1474 if (listbox_ctrl != null && dropdown_style == ComboBoxStyle.Simple) {
1475 listbox_ctrl.Location = listbox_area.Location;
1476 listbox_ctrl.CalcListBoxArea ();
1480 private void CreateComboListBox ()
1482 listbox_ctrl = new ComboListBox (this);
1483 listbox_ctrl.HighlightedIndex = SelectedIndex;
1486 internal void Draw (Rectangle clip, Graphics dc)
1488 Theme theme = ThemeEngine.Current;
1489 FlatStyle style = FlatStyle.Standard;
1490 bool is_flat = false;
1493 style = this.FlatStyle;
1494 is_flat = style == FlatStyle.Flat || style == FlatStyle.Popup;
1497 theme.ComboBoxDrawBackground (this, dc, clip, style);
1499 int border = theme.Border3DSize.Width;
1501 // No edit control, we paint the edit ourselves
1502 if (dropdown_style == ComboBoxStyle.DropDownList) {
1503 DrawItemState state = DrawItemState.None;
1504 Rectangle item_rect = text_area;
1505 item_rect.X += border;
1506 item_rect.Y += border;
1507 item_rect.Width -= (button_area.Width + 2 * border);
1508 item_rect.Height -= 2 * border;
1511 state = DrawItemState.Selected;
1512 state |= DrawItemState.Focus;
1515 state |= DrawItemState.ComboBoxEdit;
1516 HandleDrawItem (new DrawItemEventArgs (dc, Font, item_rect, SelectedIndex, state, ForeColor, BackColor));
1519 if (show_dropdown_button) {
1520 ButtonState current_state;
1522 current_state = button_state;
1524 current_state = ButtonState.Inactive;
1526 if (is_flat || theme.ComboBoxNormalDropDownButtonHasTransparentBackground (this, current_state))
1527 dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), button_area);
1530 theme.DrawFlatStyleComboButton (dc, button_area, current_state);
1532 theme.ComboBoxDrawNormalDropDownButton (this, dc, clip, button_area, current_state);
1537 internal bool DropDownButtonEntered {
1538 get { return drop_down_button_entered; }
1540 if (drop_down_button_entered == value)
1542 drop_down_button_entered = value;
1543 if (ThemeEngine.Current.ComboBoxDropDownButtonHasHotElementStyle (this))
1544 Invalidate (button_area);
1548 internal void DropDownListBox ()
1550 DropDownButtonEntered = false;
1552 if (DropDownStyle == ComboBoxStyle.Simple)
1555 if (listbox_ctrl == null)
1556 CreateComboListBox ();
1558 listbox_ctrl.Location = PointToScreen (new Point (text_area.X, text_area.Y + text_area.Height));
1560 FindMatchOrSetIndex(SelectedIndex);
1563 if (textbox_ctrl != null)
1564 textbox_ctrl.HideAutoCompleteList ();
1567 if (listbox_ctrl.ShowWindow ())
1568 dropped_down = true;
1570 button_state = ButtonState.Pushed;
1571 if (dropdown_style == ComboBoxStyle.DropDownList)
1572 Invalidate (text_area);
1575 internal void DropDownListBoxFinished ()
1577 if (DropDownStyle == ComboBoxStyle.Simple)
1580 FindMatchOrSetIndex (SelectedIndex);
1581 button_state = ButtonState.Normal;
1582 Invalidate (button_area);
1583 dropped_down = false;
1585 OnDropDownClosed (EventArgs.Empty);
1588 * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
1589 * this causes the popup to appear under the main form. This is horrible but necessary
1592 // If the user opens a new form in an event, it will close our dropdown,
1593 // so we need a null check here
1594 if (listbox_ctrl != null) {
1595 listbox_ctrl.Dispose ();
1596 listbox_ctrl = null;
1600 private int FindStringCaseInsensitive (string search)
1602 if (search.Length == 0) {
1606 for (int i = 0; i < Items.Count; i++)
1608 if (String.Compare (GetItemText (Items[i]), 0, search, 0, search.Length, true) == 0)
1615 // Search in the list for the substring, starting the search at the list
1616 // position specified, the search wraps thus covering all the list.
1617 internal int FindStringCaseInsensitive (string search, int start_index)
1619 if (search.Length == 0) {
1622 // Accept from first item to after last item. i.e. all cases of (SelectedIndex+1).
1623 if (start_index < 0 || start_index > Items.Count)
1624 throw new ArgumentOutOfRangeException("start_index");
1626 for (int i = 0; i < Items.Count; i++) {
1627 int index = (i + start_index) % Items.Count;
1628 if (String.Compare (GetItemText (Items [index]), 0, search, 0, search.Length, true) == 0)
1635 internal override bool IsInputCharInternal (char charCode)
1640 internal override ContextMenu ContextMenuInternal {
1642 return base.ContextMenuInternal;
1645 base.ContextMenuInternal = value;
1646 if (textbox_ctrl != null) {
1647 textbox_ctrl.ContextMenu = value;
1652 internal void RestoreContextMenu ()
1654 textbox_ctrl.RestoreContextMenu ();
1657 private void OnKeyDownCB(object sender, KeyEventArgs e)
1659 if (Items.Count == 0)
1662 // for keyboard navigation, we have to do our own scroll, since
1663 // the default behaviour for the SelectedIndex property is a little different,
1664 // setting the selected index in the top always
1670 FindMatchOrSetIndex(Math.Max(SelectedIndex - 1, 0));
1673 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1674 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1678 if ((e.Modifiers & Keys.Alt) == Keys.Alt)
1681 FindMatchOrSetIndex(Math.Min(SelectedIndex + 1, Items.Count - 1));
1684 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1685 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1689 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1693 SetSelectedIndex (Math.Max (SelectedIndex - offset, 0), true);
1696 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1697 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1701 if (SelectedIndex == -1) {
1703 if (dropdown_style != ComboBoxStyle.Simple)
1707 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1711 SetSelectedIndex (Math.Min (SelectedIndex + offset, Items.Count - 1), true);
1714 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1715 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1720 if (listbox_ctrl != null && listbox_ctrl.Visible)
1721 DropDownListBoxFinished ();
1725 if (dropdown_style == ComboBoxStyle.DropDownList) {
1729 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1730 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1735 if (dropdown_style == ComboBoxStyle.DropDownList) {
1736 SetSelectedIndex (Items.Count - 1, true);
1739 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1740 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1749 void SetSelectedIndex (int value, bool supressAutoScroll)
1751 if (selected_index == value)
1754 if (value <= -2 || value >= Items.Count)
1755 throw new ArgumentOutOfRangeException ("SelectedIndex");
1757 selected_index = value;
1759 if (dropdown_style != ComboBoxStyle.DropDownList) {
1761 SetControlText (string.Empty, false, supressAutoScroll);
1763 SetControlText (GetItemText (Items [value]), false, supressAutoScroll);
1766 if (DropDownStyle == ComboBoxStyle.DropDownList)
1769 if (listbox_ctrl != null)
1770 listbox_ctrl.HighlightedIndex = value;
1772 OnSelectedValueChanged (EventArgs.Empty);
1773 OnSelectedIndexChanged (EventArgs.Empty);
1774 OnSelectedItemChanged (EventArgs.Empty);
1777 // If no item is currently selected, and an item is found matching the text
1778 // in the textbox, then selected that item. Otherwise the item at the given
1779 // index is selected.
1780 private void FindMatchOrSetIndex(int index)
1783 if (SelectedIndex == -1 && Text.Length != 0)
1784 match = FindStringCaseInsensitive(Text);
1786 SetSelectedIndex (match, true);
1788 SetSelectedIndex (index, true);
1791 void OnMouseDownCB (object sender, MouseEventArgs e)
1794 if (DropDownStyle == ComboBoxStyle.DropDownList)
1795 area = ClientRectangle;
1799 if (area.Contains (e.X, e.Y)) {
1800 if (Items.Count > 0)
1803 button_state = ButtonState.Pushed;
1804 OnDropDown (EventArgs.Empty);
1807 Invalidate (button_area);
1813 void OnMouseEnter (object sender, EventArgs e)
1815 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this))
1819 void OnMouseLeave (object sender, EventArgs e)
1821 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this)) {
1822 drop_down_button_entered = false;
1825 if (show_dropdown_button)
1826 DropDownButtonEntered = false;
1830 void OnMouseMoveCB (object sender, MouseEventArgs e)
1832 if (show_dropdown_button && !dropped_down)
1833 DropDownButtonEntered = button_area.Contains (e.Location);
1835 if (DropDownStyle == ComboBoxStyle.Simple)
1838 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1839 Point location = listbox_ctrl.PointToClient (Control.MousePosition);
1840 if (listbox_ctrl.ClientRectangle.Contains (location))
1841 listbox_ctrl.Capture = true;
1845 void OnMouseUpCB (object sender, MouseEventArgs e)
1849 button_state = ButtonState.Normal;
1850 Invalidate (button_area);
1852 OnClick (EventArgs.Empty);
1855 listbox_ctrl.Capture = true;
1858 private void OnMouseWheelCB (object sender, MouseEventArgs me)
1860 if (Items.Count == 0)
1863 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1864 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
1865 listbox_ctrl.Scroll (-lines);
1867 int lines = me.Delta / 120;
1868 int index = SelectedIndex - lines;
1871 else if (index >= Items.Count)
1872 index = Items.Count - 1;
1873 SelectedIndex = index;
1877 internal override void OnPaintInternal (PaintEventArgs pevent)
1879 if (suspend_ctrlupdate)
1882 Draw (ClientRectangle, pevent.Graphics);
1885 private void OnTextBoxClick (object sender, EventArgs e)
1890 private void OnTextChangedEdit (object sender, EventArgs e)
1892 if (process_textchanged_event == false)
1895 int item = FindStringCaseInsensitive (textbox_ctrl.Text);
1898 // Setting base.Text below will raise this event
1899 // if we found something
1900 OnTextChanged (EventArgs.Empty);
1904 if (listbox_ctrl != null) {
1906 if (process_texchanged_autoscroll)
1907 listbox_ctrl.EnsureTop (item);
1910 base.Text = textbox_ctrl.Text;
1913 private void OnTextKeyPress (object sender, KeyPressEventArgs e)
1915 selected_index = -1;
1916 if (listbox_ctrl != null)
1917 listbox_ctrl.HighlightedIndex = -1;
1920 internal void SetControlText (string s, bool suppressTextChanged)
1922 SetControlText (s, suppressTextChanged, false);
1925 internal void SetControlText (string s, bool suppressTextChanged, bool supressAutoScroll)
1927 if (suppressTextChanged)
1928 process_textchanged_event = false;
1929 if (supressAutoScroll)
1930 process_texchanged_autoscroll = false;
1932 textbox_ctrl.Text = s;
1933 textbox_ctrl.SelectAll ();
1934 process_textchanged_event = true;
1935 process_texchanged_autoscroll = true;
1938 void UpdateComboBoxBounds ()
1940 if (requested_height == -1)
1943 // Save the requested height since set bounds can destroy it
1944 int save_height = requested_height;
1945 SetBounds (bounds.X, bounds.Y, bounds.Width, SnapHeight (requested_height),
1946 BoundsSpecified.Height);
1947 requested_height = save_height;
1950 int SnapHeight (int height)
1952 if (DropDownStyle == ComboBoxStyle.Simple && height > PreferredHeight) {
1953 if (IntegralHeight) {
1954 int border = ThemeEngine.Current.Border3DSize.Height;
1955 int lb_height = (height - PreferredHeight - 2) - border * 2;
1956 if (lb_height > ItemHeight) {
1957 int partial = (lb_height) % ItemHeight;
1959 } else if (lb_height < ItemHeight)
1960 height = PreferredHeight;
1963 height = PreferredHeight;
1968 private void UpdatedItems ()
1970 if (listbox_ctrl != null) {
1971 listbox_ctrl.UpdateLastVisibleItem ();
1972 listbox_ctrl.CalcListBoxArea ();
1973 listbox_ctrl.Refresh ();
1977 #endregion Private Methods
1979 [ListBindableAttribute (false)]
1980 public class ObjectCollection : IList, ICollection, IEnumerable
1983 private ComboBox owner;
1984 internal ArrayList object_items = new ArrayList ();
1986 #region UIA Framework Events
1990 // We are using Reflection to add/remove internal events.
1991 // Class ListProvider uses the events.
1993 //Event used to generate UIA StructureChangedEvent
1994 static object UIACollectionChangedEvent = new object ();
1996 internal event CollectionChangeEventHandler UIACollectionChanged {
1997 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
1998 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
2001 internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
2003 CollectionChangeEventHandler eh
2004 = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
2010 #endregion UIA Framework Events
2012 public ObjectCollection (ComboBox owner)
2017 #region Public Properties
2019 get { return object_items.Count; }
2022 public bool IsReadOnly {
2023 get { return false; }
2027 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2028 public virtual object this [int index] {
2030 if (index < 0 || index >= Count)
2031 throw new ArgumentOutOfRangeException ("index");
2033 return object_items[index];
2036 if (index < 0 || index >= Count)
2037 throw new ArgumentOutOfRangeException ("index");
2039 throw new ArgumentNullException ("value");
2042 //UIA Framework event: Item Removed
2043 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, object_items [index]));
2046 object_items[index] = value;
2049 //UIA Framework event: Item Added
2050 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, value));
2053 if (owner.listbox_ctrl != null)
2054 owner.listbox_ctrl.InvalidateItem (index);
2055 if (index == owner.SelectedIndex) {
2056 if (owner.textbox_ctrl == null)
2059 owner.textbox_ctrl.SelectedText = value.ToString ();
2064 bool ICollection.IsSynchronized {
2065 get { return false; }
2068 object ICollection.SyncRoot {
2069 get { return this; }
2072 bool IList.IsFixedSize {
2073 get { return false; }
2076 #endregion Public Properties
2078 #region Public Methods
2079 public int Add (object item)
2083 idx = AddItem (item);
2084 owner.UpdatedItems ();
2088 public void AddRange (object[] items)
2091 throw new ArgumentNullException ("items");
2093 foreach (object mi in items)
2096 owner.UpdatedItems ();
2099 public void Clear ()
2101 owner.selected_index = -1;
2102 object_items.Clear ();
2103 owner.UpdatedItems ();
2107 //UIA Framework event: Items list cleared
2108 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, null));
2112 public bool Contains (object value)
2115 throw new ArgumentNullException ("value");
2117 return object_items.Contains (value);
2121 public void CopyTo (object [] destination, int arrayIndex)
2123 object_items.CopyTo (destination, arrayIndex);
2126 void ICollection.CopyTo (Array destination, int index)
2128 object_items.CopyTo (destination, index);
2131 public void CopyTo (object [] dest, int arrayIndex)
2133 object_items.CopyTo (dest, arrayIndex);
2136 void ICollection.CopyTo (Array dest, int index)
2138 object_items.CopyTo (dest, index);
2142 public IEnumerator GetEnumerator ()
2144 return object_items.GetEnumerator ();
2147 int IList.Add (object item)
2152 public int IndexOf (object value)
2155 throw new ArgumentNullException ("value");
2157 return object_items.IndexOf (value);
2160 public void Insert (int index, object item)
2162 if (index < 0 || index > Count)
2163 throw new ArgumentOutOfRangeException ("index");
2165 throw new ArgumentNullException ("item");
2167 owner.BeginUpdate ();
2172 object_items.Insert (index, item);
2174 //UIA Framework event: Item added
2175 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2179 owner.EndUpdate (); // Calls UpdatedItems
2182 public void Remove (object value)
2187 if (IndexOf (value) == owner.SelectedIndex)
2188 owner.SelectedIndex = -1;
2190 RemoveAt (IndexOf (value));
2193 public void RemoveAt (int index)
2195 if (index < 0 || index >= Count)
2196 throw new ArgumentOutOfRangeException ("index");
2198 if (index == owner.SelectedIndex)
2199 owner.SelectedIndex = -1;
2202 object removed = object_items [index];
2206 object_items.RemoveAt (index);
2207 owner.UpdatedItems ();
2210 //UIA Framework event: Item removed
2211 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, removed));
2214 #endregion Public Methods
2216 #region Private Methods
2217 private int AddItem (object item)
2220 throw new ArgumentNullException ("item");
2224 foreach (object o in object_items) {
2225 if (String.Compare (item.ToString (), o.ToString ()) < 0) {
2226 object_items.Insert (index, item);
2228 // If we added the new item before the selectedindex
2229 // bump the selectedindex by one, behavior differs if
2230 // Handle has not been created.
2231 if (index <= owner.selected_index && owner.IsHandleCreated)
2232 owner.selected_index++;
2235 //UIA Framework event: Item added
2236 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2244 object_items.Add (item);
2247 //UIA Framework event: Item added
2248 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2251 return object_items.Count - 1;
2254 internal void AddRange (IList items)
2256 foreach (object mi in items)
2259 owner.UpdatedItems ();
2262 internal void Sort ()
2264 // If the objects the user put here don't have their own comparer,
2265 // use one that compares based on the object's ToString
2266 if (object_items.Count > 0 && object_items[0] is IComparer)
2267 object_items.Sort ();
2269 object_items.Sort (new ObjectComparer (owner));
2272 private class ObjectComparer : IComparer
2274 private ListControl owner;
2276 public ObjectComparer (ListControl owner)
2281 #region IComparer Members
2282 public int Compare (object x, object y)
2284 return string.Compare (owner.GetItemText (x), owner.GetItemText (y));
2288 #endregion Private Methods
2291 internal class ComboTextBox : TextBox {
2293 private ComboBox owner;
2295 public ComboTextBox (ComboBox owner)
2298 ShowSelection = false;
2299 HideSelection = false;
2301 owner.LostFocus += OwnerLostFocusHandler;
2306 void OwnerLostFocusHandler (object o, EventArgs args)
2308 if (IsAutoCompleteAvailable)
2312 protected override void OnKeyDown (KeyEventArgs args)
2314 if (args.KeyCode == Keys.Enter && IsAutoCompleteAvailable)
2317 base.OnKeyDown (args);
2320 internal override void OnAutoCompleteValueSelected (EventArgs args)
2322 base.OnAutoCompleteValueSelected (args);
2327 internal void SetSelectable (bool selectable)
2329 SetStyle (ControlStyles.Selectable, selectable);
2332 internal void ActivateCaret (bool active)
2335 document.CaretHasFocus ();
2337 document.CaretLostFocus ();
2341 internal override void OnTextUpdate ()
2343 base.OnTextUpdate ();
2344 owner.OnTextUpdate (EventArgs.Empty);
2348 protected override void OnGotFocus (EventArgs e)
2350 owner.Select (false, true);
2353 protected override void OnLostFocus (EventArgs e)
2355 owner.Select (false, true);
2358 public override bool Focused {
2360 return owner.Focused;
2364 internal override bool ActivateOnShow { get { return false; } }
2367 internal class ComboListBox : Control
2369 private ComboBox owner;
2370 private VScrollBarLB vscrollbar_ctrl;
2371 private int top_item; /* First item that we show the in the current page */
2372 private int last_item; /* Last visible item */
2373 internal int page_size; /* Number of listbox items per page */
2374 private Rectangle textarea_drawable; /* Rectangle of the drawable text area */
2376 internal enum ItemNavigation
2386 #region UIA Framework: Properties
2388 internal int UIATopItem {
2389 get { return top_item; }
2392 internal int UIALastItem {
2393 get { return last_item; }
2396 internal ScrollBar UIAVScrollBar {
2397 get { return vscrollbar_ctrl; }
2402 class VScrollBarLB : VScrollBar
2404 public VScrollBarLB ()
2408 internal override bool InternalCapture {
2409 get { return Capture; }
2413 public void FireMouseDown (MouseEventArgs e)
2418 e = TranslateEvent (e);
2422 public void FireMouseUp (MouseEventArgs e)
2427 e = TranslateEvent (e);
2431 public void FireMouseMove (MouseEventArgs e)
2436 e = TranslateEvent (e);
2440 MouseEventArgs TranslateEvent (MouseEventArgs e)
2442 Point loc = PointToClient (Control.MousePosition);
2443 return new MouseEventArgs (e.Button, e.Clicks, loc.X, loc.Y, e.Delta);
2447 public ComboListBox (ComboBox owner)
2454 MouseWheel += new MouseEventHandler (OnMouseWheelCLB);
2456 SetStyle (ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
2457 SetStyle (ControlStyles.ResizeRedraw | ControlStyles.Opaque, true);
2459 this.is_visible = false;
2461 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2462 InternalBorderStyle = BorderStyle.Fixed3D;
2464 InternalBorderStyle = BorderStyle.FixedSingle;
2467 protected override CreateParams CreateParams
2470 CreateParams cp = base.CreateParams;
2471 if (owner == null || owner.DropDownStyle == ComboBoxStyle.Simple)
2474 cp.Style ^= (int)WindowStyles.WS_CHILD;
2475 cp.Style ^= (int)WindowStyles.WS_VISIBLE;
2476 cp.Style |= (int)WindowStyles.WS_POPUP;
2477 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW | (int) WindowExStyles.WS_EX_TOPMOST;
2482 internal override bool InternalCapture {
2491 internal override bool ActivateOnShow { get { return false; } }
2492 #region Private Methods
2494 // Calcs the listbox area
2495 internal void CalcListBoxArea ()
2498 bool show_scrollbar = false;
2500 if (owner.DropDownStyle == ComboBoxStyle.Simple) {
2501 Rectangle area = owner.listbox_area;
2503 height = area.Height;
2505 // No calculation needed
2506 if (height <= 0 || width <= 0)
2509 else { // DropDown or DropDownList
2511 width = owner.DropDownWidth;
2512 int count = (owner.Items.Count <= owner.MaxDropDownItems) ? owner.Items.Count : owner.MaxDropDownItems;
2514 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2516 for (int i = 0; i < count; i++) {
2517 height += owner.GetItemHeight (i);
2522 height = owner.DropDownHeight == default_drop_down_height ? owner.ItemHeight * count : owner.DropDownHeight;
2524 height = owner.ItemHeight * count;
2529 page_size = Math.Max (height / owner.ItemHeight, 1);
2531 ComboBoxStyle dropdown_style = owner.DropDownStyle;
2532 if ((dropdown_style != ComboBoxStyle.Simple && owner.Items.Count <= owner.MaxDropDownItems)
2533 || (dropdown_style == ComboBoxStyle.Simple && owner.Items.Count * owner.ItemHeight < height)) {
2535 if (vscrollbar_ctrl != null)
2536 vscrollbar_ctrl.Visible = false;
2537 if (dropdown_style != ComboBoxStyle.Simple)
2538 height = owner.ItemHeight * owner.items.Count;
2540 /* Need vertical scrollbar */
2541 if (vscrollbar_ctrl == null) {
2542 vscrollbar_ctrl = new VScrollBarLB ();
2543 vscrollbar_ctrl.Minimum = 0;
2544 vscrollbar_ctrl.SmallChange = 1;
2545 vscrollbar_ctrl.LargeChange = 1;
2546 vscrollbar_ctrl.Maximum = 0;
2547 vscrollbar_ctrl.ValueChanged += new EventHandler (VerticalScrollEvent);
2548 Controls.AddImplicit (vscrollbar_ctrl);
2551 vscrollbar_ctrl.Dock = DockStyle.Right;
2553 vscrollbar_ctrl.Maximum = owner.Items.Count - 1;
2555 int large = page_size;
2557 int large = (dropdown_style == ComboBoxStyle.Simple ? page_size : owner.maxdrop_items) - 1;
2561 vscrollbar_ctrl.LargeChange = large;
2562 show_scrollbar = vscrollbar_ctrl.Visible = true;
2564 int hli = HighlightedIndex;
2566 hli = Math.Min (hli, vscrollbar_ctrl.Maximum);
2567 vscrollbar_ctrl.Value = hli;
2571 Size = new Size (width, height);
2572 textarea_drawable = ClientRectangle;
2573 textarea_drawable.Width = width;
2574 textarea_drawable.Height = height;
2576 if (vscrollbar_ctrl != null && show_scrollbar)
2577 textarea_drawable.Width -= vscrollbar_ctrl.Width;
2579 last_item = LastVisibleItem ();
2582 private void Draw (Rectangle clip, Graphics dc)
2584 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (owner.BackColor), clip);
2586 if (owner.Items.Count > 0) {
2588 for (int i = top_item; i <= last_item; i++) {
2589 Rectangle item_rect = GetItemDisplayRectangle (i, top_item);
2591 if (!clip.IntersectsWith (item_rect))
2594 DrawItemState state = DrawItemState.None;
2596 if (i == HighlightedIndex) {
2597 state |= DrawItemState.Selected;
2599 if (owner.DropDownStyle == ComboBoxStyle.DropDownList) {
2600 state |= DrawItemState.Focus;
2604 owner.HandleDrawItem (new DrawItemEventArgs (dc, owner.Font, item_rect,
2605 i, state, owner.ForeColor, owner.BackColor));
2610 int highlighted_index = -1;
2612 public int HighlightedIndex {
2613 get { return highlighted_index; }
2615 if (highlighted_index == value)
2618 if (highlighted_index != -1 && highlighted_index < this.owner.Items.Count)
2619 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2620 highlighted_index = value;
2621 if (highlighted_index != -1)
2622 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2626 private Rectangle GetItemDisplayRectangle (int index, int top_index)
2628 if (index < 0 || index >= owner.Items.Count)
2629 throw new ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
2631 Rectangle item_rect = new Rectangle ();
2632 int height = owner.GetItemHeight (index);
2635 item_rect.Width = textarea_drawable.Width;
2636 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2638 for (int i = top_index; i < index; i++)
2639 item_rect.Y += owner.GetItemHeight (i);
2641 item_rect.Y = height * (index - top_index);
2643 item_rect.Height = height;
2647 public void HideWindow ()
2649 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2654 owner.DropDownListBoxFinished ();
2657 private int IndexFromPointDisplayRectangle (int x, int y)
2659 for (int i = top_item; i <= last_item; i++) {
2660 if (GetItemDisplayRectangle (i, top_item).Contains (x, y) == true)
2667 public void InvalidateItem (int index)
2670 Invalidate (GetItemDisplayRectangle (index, top_item));
2673 public int LastVisibleItem ()
2675 Rectangle item_rect;
2676 int top_y = textarea_drawable.Y + textarea_drawable.Height;
2679 for (i = top_item; i < owner.Items.Count; i++) {
2680 item_rect = GetItemDisplayRectangle (i, top_item);
2681 if (item_rect.Y + item_rect.Height > top_y) {
2688 public void SetTopItem (int item)
2690 if (top_item == item)
2693 UpdateLastVisibleItem ();
2697 public int FirstVisibleItem ()
2702 public void EnsureTop (int item)
2704 if (owner.Items.Count == 0)
2706 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2709 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2712 else if (item < vscrollbar_ctrl.Minimum)
2713 item = vscrollbar_ctrl.Minimum;
2715 vscrollbar_ctrl.Value = item;
2718 bool scrollbar_grabbed = false;
2722 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.is_visible)
2725 return vscrollbar_ctrl.Bounds.Contains (PointToClient (Control.MousePosition));
2729 protected override void OnMouseDown (MouseEventArgs e)
2732 vscrollbar_ctrl.FireMouseDown (e);
2733 scrollbar_grabbed = true;
2737 protected override void OnMouseMove (MouseEventArgs e)
2739 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2742 if (scrollbar_grabbed || (!Capture && InScrollBar)) {
2743 vscrollbar_ctrl.FireMouseMove (e);
2747 Point pt = PointToClient (Control.MousePosition);
2748 int index = IndexFromPointDisplayRectangle (pt.X, pt.Y);
2751 HighlightedIndex = index;
2754 protected override void OnMouseUp (MouseEventArgs e)
2756 int index = IndexFromPointDisplayRectangle (e.X, e.Y);
2758 if (scrollbar_grabbed) {
2759 vscrollbar_ctrl.FireMouseUp (e);
2760 scrollbar_grabbed = false;
2762 HighlightedIndex = index;
2771 bool is_change = owner.SelectedIndex != index;
2773 owner.SetSelectedIndex (index, true);
2774 owner.OnSelectionChangeCommitted (new EventArgs ());
2776 // If the user selected the already selected item, SelectedIndex
2777 // won't fire these events, but .Net does, so we do it here
2779 owner.OnSelectedValueChanged (EventArgs.Empty);
2780 owner.OnSelectedIndexChanged (EventArgs.Empty);
2786 internal override void OnPaintInternal (PaintEventArgs pevent)
2788 Draw (pevent.ClipRectangle,pevent.Graphics);
2791 public bool ShowWindow ()
2793 if (owner.DropDownStyle == ComboBoxStyle.Simple && owner.Items.Count == 0)
2796 HighlightedIndex = owner.SelectedIndex;
2802 owner.OnDropDown (EventArgs.Empty);
2806 public void UpdateLastVisibleItem ()
2808 last_item = LastVisibleItem ();
2811 public void Scroll (int delta)
2813 if (delta == 0 || vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2816 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2818 int val = vscrollbar_ctrl.Value + delta;
2821 else if (val < vscrollbar_ctrl.Minimum)
2822 val = vscrollbar_ctrl.Minimum;
2823 vscrollbar_ctrl.Value = val;
2826 private void OnMouseWheelCLB (object sender, MouseEventArgs me)
2828 if (owner.Items.Count == 0)
2831 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
2836 private void VerticalScrollEvent (object sender, EventArgs e)
2838 if (top_item == vscrollbar_ctrl.Value)
2841 top_item = vscrollbar_ctrl.Value;
2842 UpdateLastVisibleItem ();
2846 protected override void WndProc(ref Message m) {
2847 if (m.Msg == (int)Msg.WM_SETFOCUS) {
2848 owner.Select (false, true);
2850 base.WndProc (ref m);
2853 #endregion Private Methods