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 // Call our own handler first and send the message to the TextBox if still needed
1400 if (!ProcessKeyMessage (ref m) && textbox_ctrl != null)
1401 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1403 case Msg.WM_MOUSELEAVE:
1404 Point location = PointToClient (Control.MousePosition);
1405 if (ClientRectangle.Contains (location))
1411 base.WndProc (ref m);
1414 #endregion Public Methods
1416 #region Private Methods
1418 void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) {
1419 if(auto_complete_source == AutoCompleteSource.CustomSource) {
1420 //FIXME: handle add, remove and refresh events in AutoComplete algorithm.
1425 internal override bool InternalCapture {
1426 get { return Capture; }
1430 void LayoutComboBox ()
1432 int border = ThemeEngine.Current.Border3DSize.Width;
1434 text_area = ClientRectangle;
1435 text_area.Height = PreferredHeight;
1437 listbox_area = ClientRectangle;
1438 listbox_area.Y = text_area.Bottom + 3;
1439 listbox_area.Height -= (text_area.Height + 2);
1441 Rectangle prev_button_area = button_area;
1443 if (DropDownStyle == ComboBoxStyle.Simple)
1444 button_area = Rectangle.Empty;
1446 button_area = text_area;
1447 button_area.X = text_area.Right - button_width - border;
1448 button_area.Y = text_area.Y + border;
1449 button_area.Width = button_width;
1450 button_area.Height = text_area.Height - 2 * border;
1452 if (flat_style == FlatStyle.Popup || flat_style == FlatStyle.Flat) {
1453 button_area.Inflate (1, 1);
1455 button_area.Width -= 2;
1460 if (button_area != prev_button_area) {
1461 prev_button_area.Y -= border;
1462 prev_button_area.Width += border;
1463 prev_button_area.Height += 2 * border;
1464 Invalidate (prev_button_area);
1465 Invalidate (button_area);
1468 if (textbox_ctrl != null) {
1469 int text_border = border + 1;
1470 textbox_ctrl.Location = new Point (text_area.X + text_border, text_area.Y + text_border);
1471 textbox_ctrl.Width = text_area.Width - button_area.Width - text_border * 2;
1472 textbox_ctrl.Height = text_area.Height - text_border * 2;
1475 if (listbox_ctrl != null && dropdown_style == ComboBoxStyle.Simple) {
1476 listbox_ctrl.Location = listbox_area.Location;
1477 listbox_ctrl.CalcListBoxArea ();
1481 private void CreateComboListBox ()
1483 listbox_ctrl = new ComboListBox (this);
1484 listbox_ctrl.HighlightedIndex = SelectedIndex;
1487 internal void Draw (Rectangle clip, Graphics dc)
1489 Theme theme = ThemeEngine.Current;
1490 FlatStyle style = FlatStyle.Standard;
1491 bool is_flat = false;
1494 style = this.FlatStyle;
1495 is_flat = style == FlatStyle.Flat || style == FlatStyle.Popup;
1498 theme.ComboBoxDrawBackground (this, dc, clip, style);
1500 int border = theme.Border3DSize.Width;
1502 // No edit control, we paint the edit ourselves
1503 if (dropdown_style == ComboBoxStyle.DropDownList) {
1504 DrawItemState state = DrawItemState.None;
1505 Rectangle item_rect = text_area;
1506 item_rect.X += border;
1507 item_rect.Y += border;
1508 item_rect.Width -= (button_area.Width + 2 * border);
1509 item_rect.Height -= 2 * border;
1512 state = DrawItemState.Selected;
1513 state |= DrawItemState.Focus;
1516 state |= DrawItemState.ComboBoxEdit;
1517 HandleDrawItem (new DrawItemEventArgs (dc, Font, item_rect, SelectedIndex, state, ForeColor, BackColor));
1520 if (show_dropdown_button) {
1521 ButtonState current_state;
1523 current_state = button_state;
1525 current_state = ButtonState.Inactive;
1527 if (is_flat || theme.ComboBoxNormalDropDownButtonHasTransparentBackground (this, current_state))
1528 dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), button_area);
1531 theme.DrawFlatStyleComboButton (dc, button_area, current_state);
1533 theme.ComboBoxDrawNormalDropDownButton (this, dc, clip, button_area, current_state);
1538 internal bool DropDownButtonEntered {
1539 get { return drop_down_button_entered; }
1541 if (drop_down_button_entered == value)
1543 drop_down_button_entered = value;
1544 if (ThemeEngine.Current.ComboBoxDropDownButtonHasHotElementStyle (this))
1545 Invalidate (button_area);
1549 internal void DropDownListBox ()
1551 DropDownButtonEntered = false;
1553 if (DropDownStyle == ComboBoxStyle.Simple)
1556 if (listbox_ctrl == null)
1557 CreateComboListBox ();
1559 listbox_ctrl.Location = PointToScreen (new Point (text_area.X, text_area.Y + text_area.Height));
1561 FindMatchOrSetIndex(SelectedIndex);
1564 if (textbox_ctrl != null)
1565 textbox_ctrl.HideAutoCompleteList ();
1568 if (listbox_ctrl.ShowWindow ())
1569 dropped_down = true;
1571 button_state = ButtonState.Pushed;
1572 if (dropdown_style == ComboBoxStyle.DropDownList)
1573 Invalidate (text_area);
1576 internal void DropDownListBoxFinished ()
1578 if (DropDownStyle == ComboBoxStyle.Simple)
1581 FindMatchOrSetIndex (SelectedIndex);
1582 button_state = ButtonState.Normal;
1583 Invalidate (button_area);
1584 dropped_down = false;
1586 OnDropDownClosed (EventArgs.Empty);
1589 * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
1590 * this causes the popup to appear under the main form. This is horrible but necessary
1593 // If the user opens a new form in an event, it will close our dropdown,
1594 // so we need a null check here
1595 if (listbox_ctrl != null) {
1596 listbox_ctrl.Dispose ();
1597 listbox_ctrl = null;
1601 private int FindStringCaseInsensitive (string search)
1603 if (search.Length == 0) {
1607 for (int i = 0; i < Items.Count; i++)
1609 if (String.Compare (GetItemText (Items[i]), 0, search, 0, search.Length, true) == 0)
1616 // Search in the list for the substring, starting the search at the list
1617 // position specified, the search wraps thus covering all the list.
1618 internal int FindStringCaseInsensitive (string search, int start_index)
1620 if (search.Length == 0) {
1623 // Accept from first item to after last item. i.e. all cases of (SelectedIndex+1).
1624 if (start_index < 0 || start_index > Items.Count)
1625 throw new ArgumentOutOfRangeException("start_index");
1627 for (int i = 0; i < Items.Count; i++) {
1628 int index = (i + start_index) % Items.Count;
1629 if (String.Compare (GetItemText (Items [index]), 0, search, 0, search.Length, true) == 0)
1636 internal override bool IsInputCharInternal (char charCode)
1641 internal override ContextMenu ContextMenuInternal {
1643 return base.ContextMenuInternal;
1646 base.ContextMenuInternal = value;
1647 if (textbox_ctrl != null) {
1648 textbox_ctrl.ContextMenu = value;
1653 internal void RestoreContextMenu ()
1655 textbox_ctrl.RestoreContextMenu ();
1658 private void OnKeyDownCB(object sender, KeyEventArgs e)
1660 if (Items.Count == 0)
1663 // for keyboard navigation, we have to do our own scroll, since
1664 // the default behaviour for the SelectedIndex property is a little different,
1665 // setting the selected index in the top always
1671 FindMatchOrSetIndex(Math.Max(SelectedIndex - 1, 0));
1674 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1675 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1679 if ((e.Modifiers & Keys.Alt) == Keys.Alt)
1682 FindMatchOrSetIndex(Math.Min(SelectedIndex + 1, Items.Count - 1));
1685 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1686 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1690 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1694 SetSelectedIndex (Math.Max (SelectedIndex - offset, 0), true);
1697 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1698 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1702 if (SelectedIndex == -1) {
1704 if (dropdown_style != ComboBoxStyle.Simple)
1708 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1712 SetSelectedIndex (Math.Min (SelectedIndex + offset, Items.Count - 1), true);
1715 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1716 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1721 if (listbox_ctrl != null && listbox_ctrl.Visible)
1722 DropDownListBoxFinished ();
1726 if (dropdown_style == ComboBoxStyle.DropDownList) {
1730 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1731 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1736 if (dropdown_style == ComboBoxStyle.DropDownList) {
1737 SetSelectedIndex (Items.Count - 1, true);
1740 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1741 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1750 void SetSelectedIndex (int value, bool supressAutoScroll)
1752 if (selected_index == value)
1755 if (value <= -2 || value >= Items.Count)
1756 throw new ArgumentOutOfRangeException ("SelectedIndex");
1758 selected_index = value;
1760 if (dropdown_style != ComboBoxStyle.DropDownList) {
1762 SetControlText (string.Empty, false, supressAutoScroll);
1764 SetControlText (GetItemText (Items [value]), false, supressAutoScroll);
1767 if (DropDownStyle == ComboBoxStyle.DropDownList)
1770 if (listbox_ctrl != null)
1771 listbox_ctrl.HighlightedIndex = value;
1773 OnSelectedValueChanged (EventArgs.Empty);
1774 OnSelectedIndexChanged (EventArgs.Empty);
1775 OnSelectedItemChanged (EventArgs.Empty);
1778 // If no item is currently selected, and an item is found matching the text
1779 // in the textbox, then selected that item. Otherwise the item at the given
1780 // index is selected.
1781 private void FindMatchOrSetIndex(int index)
1784 if (SelectedIndex == -1 && Text.Length != 0)
1785 match = FindStringCaseInsensitive(Text);
1787 SetSelectedIndex (match, true);
1789 SetSelectedIndex (index, true);
1792 void OnMouseDownCB (object sender, MouseEventArgs e)
1795 if (DropDownStyle == ComboBoxStyle.DropDownList)
1796 area = ClientRectangle;
1800 if (area.Contains (e.X, e.Y)) {
1801 if (Items.Count > 0)
1804 button_state = ButtonState.Pushed;
1805 OnDropDown (EventArgs.Empty);
1808 Invalidate (button_area);
1814 void OnMouseEnter (object sender, EventArgs e)
1816 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this))
1820 void OnMouseLeave (object sender, EventArgs e)
1822 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this)) {
1823 drop_down_button_entered = false;
1826 if (show_dropdown_button)
1827 DropDownButtonEntered = false;
1831 void OnMouseMoveCB (object sender, MouseEventArgs e)
1833 if (show_dropdown_button && !dropped_down)
1834 DropDownButtonEntered = button_area.Contains (e.Location);
1836 if (DropDownStyle == ComboBoxStyle.Simple)
1839 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1840 Point location = listbox_ctrl.PointToClient (Control.MousePosition);
1841 if (listbox_ctrl.ClientRectangle.Contains (location))
1842 listbox_ctrl.Capture = true;
1846 void OnMouseUpCB (object sender, MouseEventArgs e)
1850 button_state = ButtonState.Normal;
1851 Invalidate (button_area);
1853 OnClick (EventArgs.Empty);
1856 listbox_ctrl.Capture = true;
1859 private void OnMouseWheelCB (object sender, MouseEventArgs me)
1861 if (Items.Count == 0)
1864 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1865 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
1866 listbox_ctrl.Scroll (-lines);
1868 int lines = me.Delta / 120;
1869 int index = SelectedIndex - lines;
1872 else if (index >= Items.Count)
1873 index = Items.Count - 1;
1874 SelectedIndex = index;
1878 internal override void OnPaintInternal (PaintEventArgs pevent)
1880 if (suspend_ctrlupdate)
1883 Draw (ClientRectangle, pevent.Graphics);
1886 private void OnTextBoxClick (object sender, EventArgs e)
1891 private void OnTextChangedEdit (object sender, EventArgs e)
1893 if (process_textchanged_event == false)
1896 int item = FindStringCaseInsensitive (textbox_ctrl.Text);
1899 // Setting base.Text below will raise this event
1900 // if we found something
1901 OnTextChanged (EventArgs.Empty);
1905 if (listbox_ctrl != null) {
1907 if (process_texchanged_autoscroll)
1908 listbox_ctrl.EnsureTop (item);
1911 base.Text = textbox_ctrl.Text;
1914 private void OnTextKeyPress (object sender, KeyPressEventArgs e)
1916 selected_index = -1;
1917 if (listbox_ctrl != null)
1918 listbox_ctrl.HighlightedIndex = -1;
1921 internal void SetControlText (string s, bool suppressTextChanged)
1923 SetControlText (s, suppressTextChanged, false);
1926 internal void SetControlText (string s, bool suppressTextChanged, bool supressAutoScroll)
1928 if (suppressTextChanged)
1929 process_textchanged_event = false;
1930 if (supressAutoScroll)
1931 process_texchanged_autoscroll = false;
1933 textbox_ctrl.Text = s;
1934 textbox_ctrl.SelectAll ();
1935 process_textchanged_event = true;
1936 process_texchanged_autoscroll = true;
1939 void UpdateComboBoxBounds ()
1941 if (requested_height == -1)
1944 // Save the requested height since set bounds can destroy it
1945 int save_height = requested_height;
1946 SetBounds (bounds.X, bounds.Y, bounds.Width, SnapHeight (requested_height),
1947 BoundsSpecified.Height);
1948 requested_height = save_height;
1951 int SnapHeight (int height)
1953 if (DropDownStyle == ComboBoxStyle.Simple && height > PreferredHeight) {
1954 if (IntegralHeight) {
1955 int border = ThemeEngine.Current.Border3DSize.Height;
1956 int lb_height = (height - PreferredHeight - 2) - border * 2;
1957 if (lb_height > ItemHeight) {
1958 int partial = (lb_height) % ItemHeight;
1960 } else if (lb_height < ItemHeight)
1961 height = PreferredHeight;
1964 height = PreferredHeight;
1969 private void UpdatedItems ()
1971 if (listbox_ctrl != null) {
1972 listbox_ctrl.UpdateLastVisibleItem ();
1973 listbox_ctrl.CalcListBoxArea ();
1974 listbox_ctrl.Refresh ();
1978 #endregion Private Methods
1980 [ListBindableAttribute (false)]
1981 public class ObjectCollection : IList, ICollection, IEnumerable
1984 private ComboBox owner;
1985 internal ArrayList object_items = new ArrayList ();
1987 #region UIA Framework Events
1991 // We are using Reflection to add/remove internal events.
1992 // Class ListProvider uses the events.
1994 //Event used to generate UIA StructureChangedEvent
1995 static object UIACollectionChangedEvent = new object ();
1997 internal event CollectionChangeEventHandler UIACollectionChanged {
1998 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
1999 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
2002 internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
2004 CollectionChangeEventHandler eh
2005 = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
2011 #endregion UIA Framework Events
2013 public ObjectCollection (ComboBox owner)
2018 #region Public Properties
2020 get { return object_items.Count; }
2023 public bool IsReadOnly {
2024 get { return false; }
2028 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2029 public virtual object this [int index] {
2031 if (index < 0 || index >= Count)
2032 throw new ArgumentOutOfRangeException ("index");
2034 return object_items[index];
2037 if (index < 0 || index >= Count)
2038 throw new ArgumentOutOfRangeException ("index");
2040 throw new ArgumentNullException ("value");
2043 //UIA Framework event: Item Removed
2044 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, object_items [index]));
2047 object_items[index] = value;
2050 //UIA Framework event: Item Added
2051 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, value));
2054 if (owner.listbox_ctrl != null)
2055 owner.listbox_ctrl.InvalidateItem (index);
2056 if (index == owner.SelectedIndex) {
2057 if (owner.textbox_ctrl == null)
2060 owner.textbox_ctrl.SelectedText = value.ToString ();
2065 bool ICollection.IsSynchronized {
2066 get { return false; }
2069 object ICollection.SyncRoot {
2070 get { return this; }
2073 bool IList.IsFixedSize {
2074 get { return false; }
2077 #endregion Public Properties
2079 #region Public Methods
2080 public int Add (object item)
2084 idx = AddItem (item, false);
2085 owner.UpdatedItems ();
2089 public void AddRange (object[] items)
2092 throw new ArgumentNullException ("items");
2094 foreach (object mi in items)
2100 owner.UpdatedItems ();
2103 public void Clear ()
2105 owner.selected_index = -1;
2106 object_items.Clear ();
2107 owner.UpdatedItems ();
2111 //UIA Framework event: Items list cleared
2112 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, null));
2116 public bool Contains (object value)
2119 throw new ArgumentNullException ("value");
2121 return object_items.Contains (value);
2125 public void CopyTo (object [] destination, int arrayIndex)
2127 object_items.CopyTo (destination, arrayIndex);
2130 void ICollection.CopyTo (Array destination, int index)
2132 object_items.CopyTo (destination, index);
2135 public void CopyTo (object [] dest, int arrayIndex)
2137 object_items.CopyTo (dest, arrayIndex);
2140 void ICollection.CopyTo (Array dest, int index)
2142 object_items.CopyTo (dest, index);
2146 public IEnumerator GetEnumerator ()
2148 return object_items.GetEnumerator ();
2151 int IList.Add (object item)
2156 public int IndexOf (object value)
2159 throw new ArgumentNullException ("value");
2161 return object_items.IndexOf (value);
2164 public void Insert (int index, object item)
2166 if (index < 0 || index > Count)
2167 throw new ArgumentOutOfRangeException ("index");
2169 throw new ArgumentNullException ("item");
2171 owner.BeginUpdate ();
2174 AddItem (item, false);
2176 object_items.Insert (index, item);
2178 //UIA Framework event: Item added
2179 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2183 owner.EndUpdate (); // Calls UpdatedItems
2186 public void Remove (object value)
2191 if (IndexOf (value) == owner.SelectedIndex)
2192 owner.SelectedIndex = -1;
2194 RemoveAt (IndexOf (value));
2197 public void RemoveAt (int index)
2199 if (index < 0 || index >= Count)
2200 throw new ArgumentOutOfRangeException ("index");
2202 if (index == owner.SelectedIndex)
2203 owner.SelectedIndex = -1;
2206 object removed = object_items [index];
2210 object_items.RemoveAt (index);
2211 owner.UpdatedItems ();
2214 //UIA Framework event: Item removed
2215 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, removed));
2218 #endregion Public Methods
2220 #region Private Methods
2221 private int AddItem (object item, bool suspend)
2223 // suspend means do not sort as we put new items in, we will do a
2224 // big sort at the end
2226 throw new ArgumentNullException ("item");
2228 if (owner.Sorted && !suspend) {
2230 foreach (object o in object_items) {
2231 if (String.Compare (item.ToString (), o.ToString ()) < 0) {
2232 object_items.Insert (index, item);
2234 // If we added the new item before the selectedindex
2235 // bump the selectedindex by one, behavior differs if
2236 // Handle has not been created.
2237 if (index <= owner.selected_index && owner.IsHandleCreated)
2238 owner.selected_index++;
2241 //UIA Framework event: Item added
2242 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2250 object_items.Add (item);
2253 //UIA Framework event: Item added
2254 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2257 return object_items.Count - 1;
2260 internal void AddRange (IList items)
2262 foreach (object mi in items)
2263 AddItem (mi, false);
2268 owner.UpdatedItems ();
2271 internal void Sort ()
2273 // If the objects the user put here don't have their own comparer,
2274 // use one that compares based on the object's ToString
2275 if (object_items.Count > 0 && object_items[0] is IComparer)
2276 object_items.Sort ();
2278 object_items.Sort (new ObjectComparer (owner));
2281 private class ObjectComparer : IComparer
2283 private ListControl owner;
2285 public ObjectComparer (ListControl owner)
2290 #region IComparer Members
2291 public int Compare (object x, object y)
2293 return string.Compare (owner.GetItemText (x), owner.GetItemText (y));
2297 #endregion Private Methods
2300 internal class ComboTextBox : TextBox {
2302 private ComboBox owner;
2304 public ComboTextBox (ComboBox owner)
2307 ShowSelection = false;
2308 HideSelection = false;
2310 owner.LostFocus += OwnerLostFocusHandler;
2315 void OwnerLostFocusHandler (object o, EventArgs args)
2317 if (IsAutoCompleteAvailable)
2321 protected override void OnKeyDown (KeyEventArgs args)
2323 if (args.KeyCode == Keys.Enter && IsAutoCompleteAvailable)
2326 base.OnKeyDown (args);
2329 internal override void OnAutoCompleteValueSelected (EventArgs args)
2331 base.OnAutoCompleteValueSelected (args);
2336 internal void SetSelectable (bool selectable)
2338 SetStyle (ControlStyles.Selectable, selectable);
2341 internal void ActivateCaret (bool active)
2344 document.CaretHasFocus ();
2346 document.CaretLostFocus ();
2350 internal override void OnTextUpdate ()
2352 base.OnTextUpdate ();
2353 owner.OnTextUpdate (EventArgs.Empty);
2357 protected override void OnGotFocus (EventArgs e)
2359 owner.Select (false, true);
2362 protected override void OnLostFocus (EventArgs e)
2364 owner.Select (false, true);
2367 public override bool Focused {
2369 return owner.Focused;
2373 internal override bool ActivateOnShow { get { return false; } }
2376 internal class ComboListBox : Control
2378 private ComboBox owner;
2379 private VScrollBarLB vscrollbar_ctrl;
2380 private int top_item; /* First item that we show the in the current page */
2381 private int last_item; /* Last visible item */
2382 internal int page_size; /* Number of listbox items per page */
2383 private Rectangle textarea_drawable; /* Rectangle of the drawable text area */
2385 internal enum ItemNavigation
2395 #region UIA Framework: Properties
2397 internal int UIATopItem {
2398 get { return top_item; }
2401 internal int UIALastItem {
2402 get { return last_item; }
2405 internal ScrollBar UIAVScrollBar {
2406 get { return vscrollbar_ctrl; }
2411 class VScrollBarLB : VScrollBar
2413 public VScrollBarLB ()
2417 internal override bool InternalCapture {
2418 get { return Capture; }
2422 public void FireMouseDown (MouseEventArgs e)
2427 e = TranslateEvent (e);
2431 public void FireMouseUp (MouseEventArgs e)
2436 e = TranslateEvent (e);
2440 public void FireMouseMove (MouseEventArgs e)
2445 e = TranslateEvent (e);
2449 MouseEventArgs TranslateEvent (MouseEventArgs e)
2451 Point loc = PointToClient (Control.MousePosition);
2452 return new MouseEventArgs (e.Button, e.Clicks, loc.X, loc.Y, e.Delta);
2456 public ComboListBox (ComboBox owner)
2463 MouseWheel += new MouseEventHandler (OnMouseWheelCLB);
2465 SetStyle (ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
2466 SetStyle (ControlStyles.ResizeRedraw | ControlStyles.Opaque, true);
2468 this.is_visible = false;
2470 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2471 InternalBorderStyle = BorderStyle.Fixed3D;
2473 InternalBorderStyle = BorderStyle.FixedSingle;
2476 protected override CreateParams CreateParams
2479 CreateParams cp = base.CreateParams;
2480 if (owner == null || owner.DropDownStyle == ComboBoxStyle.Simple)
2483 cp.Style ^= (int)WindowStyles.WS_CHILD;
2484 cp.Style ^= (int)WindowStyles.WS_VISIBLE;
2485 cp.Style |= (int)WindowStyles.WS_POPUP;
2486 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW | (int) WindowExStyles.WS_EX_TOPMOST;
2491 internal override bool InternalCapture {
2500 internal override bool ActivateOnShow { get { return false; } }
2501 #region Private Methods
2503 // Calcs the listbox area
2504 internal void CalcListBoxArea ()
2507 bool show_scrollbar;
2509 if (owner.DropDownStyle == ComboBoxStyle.Simple) {
2510 Rectangle area = owner.listbox_area;
2512 height = area.Height;
2513 show_scrollbar = owner.Items.Count * owner.ItemHeight > height;
2515 // No calculation needed
2516 if (height <= 0 || width <= 0)
2520 else { // DropDown or DropDownList
2522 width = owner.DropDownWidth;
2523 int count = (owner.Items.Count <= owner.MaxDropDownItems) ? owner.Items.Count : owner.MaxDropDownItems;
2525 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2527 for (int i = 0; i < count; i++) {
2528 height += owner.GetItemHeight (i);
2531 show_scrollbar = owner.Items.Count > owner.MaxDropDownItems;
2535 if (owner.DropDownHeight == default_drop_down_height) { // ignore DropDownHeight
2536 height = owner.ItemHeight * count;
2537 show_scrollbar = owner.Items.Count > owner.MaxDropDownItems;
2539 height = owner.DropDownHeight;
2540 show_scrollbar = (count * owner.ItemHeight) > height;
2543 height = owner.ItemHeight * count;
2544 show_scrollbar = owner.Items.Count > owner.MaxDropDownItems;
2549 page_size = Math.Max (height / owner.ItemHeight, 1);
2551 ComboBoxStyle dropdown_style = owner.DropDownStyle;
2552 if (!show_scrollbar) {
2554 if (vscrollbar_ctrl != null)
2555 vscrollbar_ctrl.Visible = false;
2556 if (dropdown_style != ComboBoxStyle.Simple)
2557 height = owner.ItemHeight * owner.items.Count;
2559 /* Need vertical scrollbar */
2560 if (vscrollbar_ctrl == null) {
2561 vscrollbar_ctrl = new VScrollBarLB ();
2562 vscrollbar_ctrl.Minimum = 0;
2563 vscrollbar_ctrl.SmallChange = 1;
2564 vscrollbar_ctrl.LargeChange = 1;
2565 vscrollbar_ctrl.Maximum = 0;
2566 vscrollbar_ctrl.ValueChanged += new EventHandler (VerticalScrollEvent);
2567 Controls.AddImplicit (vscrollbar_ctrl);
2570 vscrollbar_ctrl.Dock = DockStyle.Right;
2572 vscrollbar_ctrl.Maximum = owner.Items.Count - 1;
2574 int large = page_size;
2576 int large = (dropdown_style == ComboBoxStyle.Simple ? page_size : owner.maxdrop_items) - 1;
2580 vscrollbar_ctrl.LargeChange = large;
2581 vscrollbar_ctrl.Visible = true;
2583 int hli = HighlightedIndex;
2585 hli = Math.Min (hli, vscrollbar_ctrl.Maximum);
2586 vscrollbar_ctrl.Value = hli;
2590 Size = new Size (width, height);
2591 textarea_drawable = ClientRectangle;
2592 textarea_drawable.Width = width;
2593 textarea_drawable.Height = height;
2595 if (vscrollbar_ctrl != null && show_scrollbar)
2596 textarea_drawable.Width -= vscrollbar_ctrl.Width;
2598 last_item = LastVisibleItem ();
2601 private void Draw (Rectangle clip, Graphics dc)
2603 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (owner.BackColor), clip);
2605 if (owner.Items.Count > 0) {
2607 for (int i = top_item; i <= last_item; i++) {
2608 Rectangle item_rect = GetItemDisplayRectangle (i, top_item);
2610 if (!clip.IntersectsWith (item_rect))
2613 DrawItemState state = DrawItemState.None;
2615 if (i == HighlightedIndex) {
2616 state |= DrawItemState.Selected;
2618 if (owner.DropDownStyle == ComboBoxStyle.DropDownList) {
2619 state |= DrawItemState.Focus;
2623 owner.HandleDrawItem (new DrawItemEventArgs (dc, owner.Font, item_rect,
2624 i, state, owner.ForeColor, owner.BackColor));
2629 int highlighted_index = -1;
2631 public int HighlightedIndex {
2632 get { return highlighted_index; }
2634 if (highlighted_index == value)
2637 if (highlighted_index != -1 && highlighted_index < this.owner.Items.Count)
2638 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2639 highlighted_index = value;
2640 if (highlighted_index != -1)
2641 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2645 private Rectangle GetItemDisplayRectangle (int index, int top_index)
2647 if (index < 0 || index >= owner.Items.Count)
2648 throw new ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
2650 Rectangle item_rect = new Rectangle ();
2651 int height = owner.GetItemHeight (index);
2654 item_rect.Width = textarea_drawable.Width;
2655 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2657 for (int i = top_index; i < index; i++)
2658 item_rect.Y += owner.GetItemHeight (i);
2660 item_rect.Y = height * (index - top_index);
2662 item_rect.Height = height;
2666 public void HideWindow ()
2668 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2673 owner.DropDownListBoxFinished ();
2676 private int IndexFromPointDisplayRectangle (int x, int y)
2678 for (int i = top_item; i <= last_item; i++) {
2679 if (GetItemDisplayRectangle (i, top_item).Contains (x, y) == true)
2686 public void InvalidateItem (int index)
2689 Invalidate (GetItemDisplayRectangle (index, top_item));
2692 public int LastVisibleItem ()
2694 Rectangle item_rect;
2695 int top_y = textarea_drawable.Y + textarea_drawable.Height;
2698 for (i = top_item; i < owner.Items.Count; i++) {
2699 item_rect = GetItemDisplayRectangle (i, top_item);
2700 if (item_rect.Y + item_rect.Height > top_y) {
2707 public void SetTopItem (int item)
2709 if (top_item == item)
2712 UpdateLastVisibleItem ();
2716 public int FirstVisibleItem ()
2721 public void EnsureTop (int item)
2723 if (owner.Items.Count == 0)
2725 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2728 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2731 else if (item < vscrollbar_ctrl.Minimum)
2732 item = vscrollbar_ctrl.Minimum;
2734 vscrollbar_ctrl.Value = item;
2737 bool scrollbar_grabbed = false;
2741 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.is_visible)
2744 return vscrollbar_ctrl.Bounds.Contains (PointToClient (Control.MousePosition));
2748 protected override void OnMouseDown (MouseEventArgs e)
2751 vscrollbar_ctrl.FireMouseDown (e);
2752 scrollbar_grabbed = true;
2756 protected override void OnMouseMove (MouseEventArgs e)
2758 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2761 if (scrollbar_grabbed || (!Capture && InScrollBar)) {
2762 vscrollbar_ctrl.FireMouseMove (e);
2766 Point pt = PointToClient (Control.MousePosition);
2767 int index = IndexFromPointDisplayRectangle (pt.X, pt.Y);
2770 HighlightedIndex = index;
2773 protected override void OnMouseUp (MouseEventArgs e)
2775 int index = IndexFromPointDisplayRectangle (e.X, e.Y);
2777 if (scrollbar_grabbed) {
2778 vscrollbar_ctrl.FireMouseUp (e);
2779 scrollbar_grabbed = false;
2781 HighlightedIndex = index;
2790 bool is_change = owner.SelectedIndex != index;
2792 owner.SetSelectedIndex (index, true);
2793 owner.OnSelectionChangeCommitted (new EventArgs ());
2795 // If the user selected the already selected item, SelectedIndex
2796 // won't fire these events, but .Net does, so we do it here
2798 owner.OnSelectedValueChanged (EventArgs.Empty);
2799 owner.OnSelectedIndexChanged (EventArgs.Empty);
2805 internal override void OnPaintInternal (PaintEventArgs pevent)
2807 Draw (pevent.ClipRectangle,pevent.Graphics);
2810 public bool ShowWindow ()
2812 if (owner.DropDownStyle == ComboBoxStyle.Simple && owner.Items.Count == 0)
2815 HighlightedIndex = owner.SelectedIndex;
2821 owner.OnDropDown (EventArgs.Empty);
2825 public void UpdateLastVisibleItem ()
2827 last_item = LastVisibleItem ();
2830 public void Scroll (int delta)
2832 if (delta == 0 || vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2835 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2837 int val = vscrollbar_ctrl.Value + delta;
2840 else if (val < vscrollbar_ctrl.Minimum)
2841 val = vscrollbar_ctrl.Minimum;
2842 vscrollbar_ctrl.Value = val;
2845 private void OnMouseWheelCLB (object sender, MouseEventArgs me)
2847 if (owner.Items.Count == 0)
2850 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
2855 private void VerticalScrollEvent (object sender, EventArgs e)
2857 if (top_item == vscrollbar_ctrl.Value)
2860 top_item = vscrollbar_ctrl.Value;
2861 UpdateLastVisibleItem ();
2865 protected override void WndProc(ref Message m) {
2866 if (m.Msg == (int)Msg.WM_SETFOCUS) {
2867 owner.Select (false, true);
2869 base.WndProc (ref m);
2872 #endregion Private Methods