1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 // Copyright (c) 2004-2006 Novell, Inc.
23 // Jordi Mas i Hernandez, jordi@ximian.com
24 // Mike Kestner <mkestner@novell.com>
25 // Daniel Nauck (dna(at)mono-project(dot)de)
28 using System.Collections;
29 using System.ComponentModel;
30 using System.ComponentModel.Design;
31 using System.ComponentModel.Design.Serialization;
33 using System.Globalization;
34 using System.Reflection;
35 using System.Runtime.InteropServices;
37 namespace System.Windows.Forms
39 [DefaultProperty("Items")]
40 [DefaultEvent("SelectedIndexChanged")]
41 [Designer ("System.Windows.Forms.Design.ComboBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
43 [DefaultBindingProperty ("Text")]
44 [ClassInterface (ClassInterfaceType.AutoDispatch)]
47 public class ComboBox : ListControl
49 private DrawMode draw_mode = DrawMode.Normal;
50 private ComboBoxStyle dropdown_style;
51 private int dropdown_width = -1;
52 private int selected_index = -1;
53 private ObjectCollection items;
54 private bool suspend_ctrlupdate;
55 private int maxdrop_items = 8;
56 private bool integral_height = true;
58 private int max_length;
59 private ComboListBox listbox_ctrl;
60 private ComboTextBox textbox_ctrl;
61 private bool process_textchanged_event = true;
62 private bool item_height_specified;
63 private int item_height;
64 private int requested_height = -1;
65 private Hashtable item_heights;
66 private bool show_dropdown_button;
67 private ButtonState button_state = ButtonState.Normal;
68 private bool dropped_down;
69 private Rectangle text_area;
70 private Rectangle button_area;
71 private Rectangle listbox_area;
72 private const int button_width = 16;
73 bool drop_down_button_entered;
75 private AutoCompleteStringCollection auto_complete_custom_source = null;
76 private AutoCompleteMode auto_complete_mode = AutoCompleteMode.None;
77 private AutoCompleteSource auto_complete_source = AutoCompleteSource.None;
78 private int drop_down_height;
79 private FlatStyle flat_style;
83 public class ChildAccessibleObject : AccessibleObject {
85 public ChildAccessibleObject (ComboBox owner, IntPtr handle)
90 public override string Name {
99 items = new ObjectCollection (this);
100 DropDownStyle = ComboBoxStyle.DropDown;
101 item_height = FontHeight + 2;
102 background_color = ThemeEngine.Current.ColorWindow;
103 border_style = BorderStyle.None;
106 drop_down_height = 106;
107 flat_style = FlatStyle.Standard;
111 MouseDown += new MouseEventHandler (OnMouseDownCB);
112 MouseUp += new MouseEventHandler (OnMouseUpCB);
113 MouseMove += new MouseEventHandler (OnMouseMoveCB);
114 MouseWheel += new MouseEventHandler (OnMouseWheelCB);
115 MouseEnter += new EventHandler (OnMouseEnter);
116 MouseLeave += new EventHandler (OnMouseLeave);
117 KeyDown +=new KeyEventHandler(OnKeyDownCB);
123 [EditorBrowsable (EditorBrowsableState.Never)]
124 public new event EventHandler BackgroundImageChanged {
125 add { base.BackgroundImageChanged += value; }
126 remove { base.BackgroundImageChanged -= value; }
132 [EditorBrowsable (EditorBrowsableState.Never)]
133 public new event EventHandler BackgroundImageLayoutChanged
135 add { base.BackgroundImageLayoutChanged += value; }
136 remove { base.BackgroundImageLayoutChanged -= value; }
140 [EditorBrowsable (EditorBrowsableState.Never)]
141 public new event EventHandler DoubleClick
143 add { base.DoubleClick += value; }
144 remove { base.DoubleClick -= value; }
148 static object DrawItemEvent = new object ();
149 static object DropDownEvent = new object ();
150 static object DropDownStyleChangedEvent = new object ();
151 static object MeasureItemEvent = new object ();
152 static object SelectedIndexChangedEvent = new object ();
153 static object SelectionChangeCommittedEvent = new object ();
155 static object DropDownClosedEvent = new object ();
156 static object TextUpdateEvent = new object ();
159 public event DrawItemEventHandler DrawItem {
160 add { Events.AddHandler (DrawItemEvent, value); }
161 remove { Events.RemoveHandler (DrawItemEvent, value); }
164 public event EventHandler DropDown {
165 add { Events.AddHandler (DropDownEvent, value); }
166 remove { Events.RemoveHandler (DropDownEvent, value); }
169 public event EventHandler DropDownClosed
171 add { Events.AddHandler (DropDownClosedEvent, value); }
172 remove { Events.RemoveHandler (DropDownClosedEvent, value); }
176 public event EventHandler DropDownStyleChanged {
177 add { Events.AddHandler (DropDownStyleChangedEvent, value); }
178 remove { Events.RemoveHandler (DropDownStyleChangedEvent, value); }
181 public event MeasureItemEventHandler MeasureItem {
182 add { Events.AddHandler (MeasureItemEvent, value); }
183 remove { Events.RemoveHandler (MeasureItemEvent, value); }
187 [EditorBrowsable (EditorBrowsableState.Never)]
188 public new event EventHandler PaddingChanged
190 add { base.PaddingChanged += value; }
191 remove { base.PaddingChanged -= value; }
196 [EditorBrowsable (EditorBrowsableState.Never)]
197 public new event PaintEventHandler Paint {
198 add { base.Paint += value; }
199 remove { base.Paint -= value; }
202 public event EventHandler SelectedIndexChanged {
203 add { Events.AddHandler (SelectedIndexChangedEvent, value); }
204 remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
207 public event EventHandler SelectionChangeCommitted {
208 add { Events.AddHandler (SelectionChangeCommittedEvent, value); }
209 remove { Events.RemoveHandler (SelectionChangeCommittedEvent, value); }
212 public event EventHandler TextUpdate
214 add { Events.AddHandler (TextUpdateEvent, value); }
215 remove { Events.RemoveHandler (TextUpdateEvent, value); }
221 #region Public Properties
223 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
224 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
226 [EditorBrowsable (EditorBrowsableState.Always)]
228 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design,
229 "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
230 public AutoCompleteStringCollection AutoCompleteCustomSource {
232 if(auto_complete_custom_source == null) {
233 auto_complete_custom_source = new AutoCompleteStringCollection ();
234 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
236 return auto_complete_custom_source;
239 if(auto_complete_custom_source == value)
242 if(auto_complete_custom_source != null) //remove eventhandler from old collection
243 auto_complete_custom_source.CollectionChanged -= new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
245 auto_complete_custom_source = value;
247 if(auto_complete_custom_source != null)
248 auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
250 SetTextBoxAutoCompleteData ();
254 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
256 [EditorBrowsable (EditorBrowsableState.Always)]
257 [DefaultValue (AutoCompleteMode.None)]
258 public AutoCompleteMode AutoCompleteMode {
259 get { return auto_complete_mode; }
261 if(auto_complete_mode == value)
264 if((value < AutoCompleteMode.None) || (value > AutoCompleteMode.SuggestAppend))
265 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteMode", value));
267 auto_complete_mode = value;
268 SetTextBoxAutoCompleteData ();
272 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
274 [EditorBrowsable (EditorBrowsableState.Always)]
275 [DefaultValue (AutoCompleteSource.None)]
276 public AutoCompleteSource AutoCompleteSource {
277 get { return auto_complete_source; }
279 if(auto_complete_source == value)
282 if(!Enum.IsDefined (typeof (AutoCompleteSource), value))
283 throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteSource", value));
285 auto_complete_source = value;
286 SetTextBoxAutoCompleteData ();
290 void SetTextBoxAutoCompleteData ()
292 if (textbox_ctrl == null)
295 textbox_ctrl.AutoCompleteMode = auto_complete_mode;
297 if (auto_complete_source == AutoCompleteSource.ListItems) {
298 textbox_ctrl.AutoCompleteSource = AutoCompleteSource.CustomSource;
299 textbox_ctrl.AutoCompleteCustomSource = null;
300 textbox_ctrl.AutoCompleteInternalSource = this;
302 textbox_ctrl.AutoCompleteSource = auto_complete_source;
303 textbox_ctrl.AutoCompleteCustomSource = auto_complete_custom_source;
304 textbox_ctrl.AutoCompleteInternalSource = null;
308 public override Color BackColor {
309 get { return base.BackColor; }
311 if (base.BackColor == value)
313 base.BackColor = value;
319 [EditorBrowsable (EditorBrowsableState.Never)]
320 public override Image BackgroundImage {
321 get { return base.BackgroundImage; }
323 if (base.BackgroundImage == value)
325 base.BackgroundImage = value;
332 [EditorBrowsable (EditorBrowsableState.Never)]
333 public override ImageLayout BackgroundImageLayout {
334 get { return base.BackgroundImageLayout; }
335 set { base.BackgroundImageLayout = value; }
339 protected override CreateParams CreateParams {
340 get { return base.CreateParams;}
344 [DefaultValue ((string)null)]
345 [AttributeProvider (typeof (IListSource))]
346 [RefreshProperties (RefreshProperties.Repaint)]
347 [MWFCategory("Data")]
348 public new object DataSource {
349 get { return base.DataSource; }
350 set { base.DataSource = value; }
354 protected override Size DefaultSize {
355 get { return new Size (121, 21); }
358 [RefreshProperties(RefreshProperties.Repaint)]
359 [DefaultValue (DrawMode.Normal)]
360 [MWFCategory("Behavior")]
361 public DrawMode DrawMode {
362 get { return draw_mode; }
364 if (!Enum.IsDefined (typeof (DrawMode), value))
365 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for DrawMode", value));
367 if (draw_mode == value)
370 if (draw_mode == DrawMode.OwnerDrawVariable)
373 if (draw_mode == DrawMode.OwnerDrawVariable)
374 item_heights = new Hashtable ();
382 [EditorBrowsable (EditorBrowsableState.Always)]
383 [MWFCategory("Behavior")]
384 public int DropDownHeight {
386 return drop_down_height;
390 throw new ArgumentOutOfRangeException ("DropDownHeight", "DropDownHeight must be greater than 0.");
392 drop_down_height = value;
393 IntegralHeight = false;
398 [DefaultValue (ComboBoxStyle.DropDown)]
399 [RefreshProperties(RefreshProperties.Repaint)]
400 [MWFCategory("Appearance")]
401 public ComboBoxStyle DropDownStyle {
402 get { return dropdown_style; }
404 if (!Enum.IsDefined (typeof (ComboBoxStyle), value))
405 throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for ComboBoxStyle", value));
407 if (dropdown_style == value)
412 if (dropdown_style == ComboBoxStyle.Simple) {
413 if (listbox_ctrl != null) {
414 Controls.RemoveImplicit (listbox_ctrl);
415 listbox_ctrl.Dispose ();
420 dropdown_style = value;
422 if (dropdown_style == ComboBoxStyle.DropDownList && textbox_ctrl != null) {
423 Controls.RemoveImplicit (textbox_ctrl);
424 textbox_ctrl.Dispose ();
428 if (dropdown_style == ComboBoxStyle.Simple) {
429 show_dropdown_button = false;
431 CreateComboListBox ();
432 Controls.AddImplicit (listbox_ctrl);
433 listbox_ctrl.Visible = true;
435 // This should give us a 150 default height
436 // for Simple mode if size hasn't been set
437 // (DefaultSize doesn't work for us in this case)
438 if (requested_height == -1)
439 requested_height = 150;
441 show_dropdown_button = true;
442 button_state = ButtonState.Normal;
445 if (dropdown_style != ComboBoxStyle.DropDownList && textbox_ctrl == null) {
446 textbox_ctrl = new ComboTextBox (this);
447 object selected_item = SelectedItem;
448 if (selected_item != null)
449 textbox_ctrl.Text = GetItemText (selected_item);
450 textbox_ctrl.BorderStyle = BorderStyle.None;
451 textbox_ctrl.TextChanged += new EventHandler (OnTextChangedEdit);
452 textbox_ctrl.KeyPress += new KeyPressEventHandler (OnTextKeyPress);
453 textbox_ctrl.Click += new EventHandler (OnTextBoxClick);
454 textbox_ctrl.ContextMenu = ContextMenu;
456 if (IsHandleCreated == true)
457 Controls.AddImplicit (textbox_ctrl);
459 SetTextBoxAutoCompleteData ();
464 OnDropDownStyleChanged (EventArgs.Empty);
467 UpdateComboBoxBounds ();
472 [MWFCategory("Behavior")]
473 public int DropDownWidth {
475 if (dropdown_width == -1)
478 return dropdown_width;
481 if (dropdown_width == value)
486 throw new ArgumentOutOfRangeException ("DropDownWidth",
487 "The DropDownWidth value is less than one.");
489 throw new ArgumentException ("The DropDownWidth value is less than one.");
492 dropdown_width = value;
497 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
498 public bool DroppedDown {
500 if (dropdown_style == ComboBoxStyle.Simple)
506 if (dropdown_style == ComboBoxStyle.Simple || dropped_down == value)
512 listbox_ctrl.Hide ();
517 [DefaultValue (FlatStyle.Standard)]
519 [MWFCategory("Appearance")]
520 public FlatStyle FlatStyle {
521 get { return flat_style; }
523 if (!Enum.IsDefined (typeof (FlatStyle), value))
524 throw new InvalidEnumArgumentException ("FlatStyle", (int) value, typeof (FlatStyle));
533 public override bool Focused {
534 get { return base.Focused; }
537 public override Color ForeColor {
538 get { return base.ForeColor; }
540 if (base.ForeColor == value)
542 base.ForeColor = value;
547 [DefaultValue (true)]
549 [MWFCategory("Behavior")]
550 public bool IntegralHeight {
551 get { return integral_height; }
553 if (integral_height == value)
555 integral_height = value;
556 UpdateComboBoxBounds ();
562 [MWFCategory("Behavior")]
563 public int ItemHeight {
565 if (item_height == -1) {
566 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
567 item_height = (int) sz.Height;
574 throw new ArgumentOutOfRangeException ("ItemHeight",
575 "The item height value is less than one.");
577 throw new ArgumentException ("The item height value is less than one.");
580 item_height_specified = true;
583 UpdateComboBoxBounds ();
589 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
591 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
593 [MergableProperty (false)]
595 [MWFCategory("Data")]
596 public ComboBox.ObjectCollection Items {
597 get { return items; }
602 [MWFCategory("Behavior")]
603 public int MaxDropDownItems {
604 get { return maxdrop_items; }
606 if (maxdrop_items == value)
608 maxdrop_items = value;
613 public override Size MaximumSize {
614 get { return base.MaximumSize; }
616 base.MaximumSize = new Size (value.Width, 0);
623 [MWFCategory("Behavior")]
624 public int MaxLength {
625 get { return max_length; }
627 if (max_length == value)
632 if (dropdown_style != ComboBoxStyle.DropDownList) {
636 textbox_ctrl.MaxLength = value;
642 public override Size MinimumSize {
643 get { return base.MinimumSize; }
645 base.MinimumSize = new Size (value.Width, 0);
649 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
650 [EditorBrowsable (EditorBrowsableState.Never)]
652 public new Padding Padding {
653 get { return base.Padding; }
654 set { base.Padding = value; }
658 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
660 public int PreferredHeight {
661 get { return Font.Height + 8; }
665 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
666 public override int SelectedIndex {
667 get { return selected_index; }
669 if (selected_index == value)
672 if (value <= -2 || value >= Items.Count)
673 throw new ArgumentOutOfRangeException ("SelectedIndex");
674 selected_index = value;
676 if (dropdown_style != ComboBoxStyle.DropDownList) {
678 SetControlText (string.Empty, false);
680 SetControlText (GetItemText (Items [value]), false);
683 if (DropDownStyle == ComboBoxStyle.DropDownList)
686 if (listbox_ctrl != null)
687 listbox_ctrl.HighlightedIndex = value;
689 OnSelectedValueChanged (new EventArgs ());
690 OnSelectedIndexChanged (new EventArgs ());
691 OnSelectedItemChanged (new EventArgs ());
696 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
698 public object SelectedItem {
699 get { return selected_index == -1 ? null : Items [selected_index]; }
701 object item = selected_index == -1 ? null : Items [selected_index];
708 SelectedIndex = Items.IndexOf (value);
713 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
714 public string SelectedText {
716 if (dropdown_style == ComboBoxStyle.DropDownList)
719 string retval = textbox_ctrl.SelectedText;
722 // On 1.1, the textbox will return null, combobox returns ""
723 if (retval == null && !textbox_ctrl.IsHandleCreated)
729 if (dropdown_style == ComboBoxStyle.DropDownList)
731 textbox_ctrl.SelectedText = value;
736 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
737 public int SelectionLength {
739 if (dropdown_style == ComboBoxStyle.DropDownList)
742 int result = textbox_ctrl.SelectionLength;
743 return result == -1 ? 0 : result;
746 if (dropdown_style == ComboBoxStyle.DropDownList)
748 if (textbox_ctrl.SelectionLength == value)
750 textbox_ctrl.SelectionLength = value;
755 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
756 public int SelectionStart {
758 if (dropdown_style == ComboBoxStyle.DropDownList)
760 return textbox_ctrl.SelectionStart;
763 if (dropdown_style == ComboBoxStyle.DropDownList)
765 if (textbox_ctrl.SelectionStart == value)
767 textbox_ctrl.SelectionStart = value;
771 [DefaultValue (false)]
772 [MWFCategory("Behavior")]
774 get { return sorted; }
789 public override string Text {
791 if (dropdown_style != ComboBoxStyle.DropDownList) {
792 if (textbox_ctrl != null) {
793 return textbox_ctrl.Text;
797 if (SelectedItem != null)
798 return GetItemText (SelectedItem);
804 if (SelectedIndex == -1) {
805 if (dropdown_style != ComboBoxStyle.DropDownList)
806 SetControlText (string.Empty, false);
813 // do nothing if value exactly matches text of selected item
814 if (SelectedItem != null && string.Compare (value, GetItemText (SelectedItem), false, CultureInfo.CurrentCulture) == 0)
817 // find exact match using case-sensitive comparison, and if does
818 // not result in any match then use case-insensitive comparison
819 int index = FindStringExact (value, -1, false);
821 index = FindStringExact (value, -1, true);
824 SelectedIndex = index;
828 if (dropdown_style != ComboBoxStyle.DropDownList)
829 textbox_ctrl.Text = GetItemText (value);
833 #endregion Public Properties
835 #region Internal Properties
836 internal Rectangle ButtonArea {
837 get { return button_area; }
840 internal Rectangle TextArea {
841 get { return text_area; }
845 #region UIA Framework Properties
847 internal TextBox UIATextBox {
848 get { return textbox_ctrl; }
851 #endregion UIA Framework Properties
853 #region Public Methods
855 [Obsolete ("This method has been deprecated")]
857 protected virtual void AddItemsCore (object[] value)
862 public void BeginUpdate ()
864 suspend_ctrlupdate = true;
868 protected override AccessibleObject CreateAccessibilityInstance ()
870 return base.CreateAccessibilityInstance ();
873 protected override void CreateHandle ()
875 base.CreateHandle ();
879 protected override void Dispose (bool disposing)
882 if (listbox_ctrl != null) {
883 listbox_ctrl.Dispose ();
884 Controls.RemoveImplicit (listbox_ctrl);
888 if (textbox_ctrl != null) {
889 Controls.RemoveImplicit (textbox_ctrl);
890 textbox_ctrl.Dispose ();
895 base.Dispose (disposing);
898 public void EndUpdate ()
900 suspend_ctrlupdate = false;
905 public int FindString (string s)
907 return FindString (s, -1);
910 public int FindString (string s, int startIndex)
912 if (s == null || Items.Count == 0)
916 if (startIndex < -1 || startIndex >= Items.Count)
918 if (startIndex < -1 || startIndex >= Items.Count - 1)
920 throw new ArgumentOutOfRangeException ("startIndex");
924 if (i == (Items.Count - 1))
929 if (string.Compare (s, 0, GetItemText (Items [i]), 0, s.Length, true) == 0)
931 if (i == (Items.Count - 1))
933 } while (i != startIndex);
938 public int FindStringExact (string s)
940 return FindStringExact (s, -1);
943 public int FindStringExact (string s, int startIndex)
945 return FindStringExact (s, startIndex, true);
948 private int FindStringExact (string s, int startIndex, bool ignoreCase)
950 if (s == null || Items.Count == 0)
954 if (startIndex < -1 || startIndex >= Items.Count)
956 if (startIndex < -1 || startIndex >= Items.Count - 1)
958 throw new ArgumentOutOfRangeException ("startIndex");
962 if (i == (Items.Count - 1))
967 if (string.Compare (s, GetItemText (Items [i]), ignoreCase, CultureInfo.CurrentCulture) == 0)
969 if (i == (Items.Count - 1))
971 } while (i != startIndex);
976 public int GetItemHeight (int index)
978 if (DrawMode == DrawMode.OwnerDrawVariable && IsHandleCreated) {
980 if (index < 0 || index >= Items.Count )
981 throw new ArgumentOutOfRangeException ("The item height value is less than zero");
983 object item = Items [index];
984 if (item_heights.Contains (item))
985 return (int) item_heights [item];
987 MeasureItemEventArgs args = new MeasureItemEventArgs (DeviceContext, index, ItemHeight);
988 OnMeasureItem (args);
989 item_heights [item] = args.ItemHeight;
990 return args.ItemHeight;
996 protected override bool IsInputKey (Keys keyData)
998 switch (keyData & ~Keys.Modifiers) {
1014 protected override void OnBackColorChanged (EventArgs e)
1016 base.OnBackColorChanged (e);
1018 if (textbox_ctrl != null)
1019 textbox_ctrl.BackColor = BackColor;
1022 protected override void OnDataSourceChanged (EventArgs e)
1024 base.OnDataSourceChanged (e);
1027 if (DataSource == null || DataManager == null) {
1031 SelectedIndex = DataManager.Position;
1035 protected override void OnDisplayMemberChanged (EventArgs e)
1037 base.OnDisplayMemberChanged (e);
1039 if (DataManager == null)
1042 if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1043 SetControlText (GetItemText (Items [selected_index]), true);
1045 if (!IsHandleCreated)
1048 SelectedIndex = DataManager.Position;
1052 protected virtual void OnDrawItem (DrawItemEventArgs e)
1055 case DrawMode.OwnerDrawFixed:
1056 case DrawMode.OwnerDrawVariable:
1057 DrawItemEventHandler eh = (DrawItemEventHandler)(Events [DrawItemEvent]);
1062 ThemeEngine.Current.DrawComboBoxItem (this, e);
1067 protected virtual void OnDropDown (EventArgs e)
1069 EventHandler eh = (EventHandler)(Events [DropDownEvent]);
1075 protected virtual void OnDropDownClosed (EventArgs e)
1077 EventHandler eh = (EventHandler) Events [DropDownClosedEvent];
1083 protected virtual void OnDropDownStyleChanged (EventArgs e)
1085 EventHandler eh = (EventHandler)(Events [DropDownStyleChangedEvent]);
1090 protected override void OnFontChanged (EventArgs e)
1092 base.OnFontChanged (e);
1094 if (textbox_ctrl != null)
1095 textbox_ctrl.Font = Font;
1097 if (!item_height_specified)
1098 item_height = Font.Height + 2;
1101 UpdateComboBoxBounds ();
1106 protected override void OnForeColorChanged (EventArgs e)
1108 base.OnForeColorChanged (e);
1109 if (textbox_ctrl != null)
1110 textbox_ctrl.ForeColor = ForeColor;
1113 [EditorBrowsable(EditorBrowsableState.Advanced)]
1114 protected override void OnGotFocus (EventArgs e)
1116 if (dropdown_style == ComboBoxStyle.DropDownList) {
1117 // We draw DDL styles manually, so they require a
1118 // refresh to have their selection drawn
1122 if (textbox_ctrl != null) {
1123 textbox_ctrl.SetSelectable (false);
1124 textbox_ctrl.ShowSelection = true;
1125 textbox_ctrl.ActivateCaret (true);
1126 textbox_ctrl.SelectAll ();
1129 base.OnGotFocus (e);
1132 [EditorBrowsable(EditorBrowsableState.Advanced)]
1133 protected override void OnLostFocus (EventArgs e)
1135 if (dropdown_style == ComboBoxStyle.DropDownList) {
1136 // We draw DDL styles manually, so they require a
1137 // refresh to have their selection drawn
1141 if (listbox_ctrl != null && dropped_down) {
1142 listbox_ctrl.HideWindow ();
1145 if (textbox_ctrl != null) {
1146 textbox_ctrl.SetSelectable (true);
1147 textbox_ctrl.ActivateCaret (false);
1148 textbox_ctrl.ShowSelection = false;
1149 textbox_ctrl.SelectionLength = 0;
1152 base.OnLostFocus (e);
1155 protected override void OnHandleCreated (EventArgs e)
1157 base.OnHandleCreated (e);
1159 SetBoundsInternal (Left, Top, Width, PreferredHeight, BoundsSpecified.None);
1161 if (textbox_ctrl != null)
1162 Controls.AddImplicit (textbox_ctrl);
1165 UpdateComboBoxBounds ();
1168 protected override void OnHandleDestroyed (EventArgs e)
1170 base.OnHandleDestroyed (e);
1173 protected override void OnKeyPress (KeyPressEventArgs e)
1175 if (dropdown_style == ComboBoxStyle.DropDownList) {
1176 int index = FindStringCaseInsensitive (e.KeyChar.ToString (), SelectedIndex + 1);
1178 SelectedIndex = index;
1179 if (DroppedDown) { //Scroll into view
1180 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1181 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1182 // Or, selecting an item earlier in the list.
1183 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1184 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1189 base.OnKeyPress (e);
1192 protected virtual void OnMeasureItem (MeasureItemEventArgs e)
1194 MeasureItemEventHandler eh = (MeasureItemEventHandler)(Events [MeasureItemEvent]);
1199 protected override void OnParentBackColorChanged (EventArgs e)
1201 base.OnParentBackColorChanged (e);
1204 protected override void OnResize (EventArgs e)
1207 if (listbox_ctrl != null)
1208 listbox_ctrl.CalcListBoxArea ();
1211 protected override void OnSelectedIndexChanged (EventArgs e)
1213 base.OnSelectedIndexChanged (e);
1215 EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
1220 protected virtual void OnSelectedItemChanged (EventArgs e)
1224 protected override void OnSelectedValueChanged (EventArgs e)
1226 base.OnSelectedValueChanged (e);
1229 protected virtual void OnSelectionChangeCommitted (EventArgs e)
1231 EventHandler eh = (EventHandler)(Events [SelectionChangeCommittedEvent]);
1236 protected override void RefreshItem (int index)
1238 if (index < 0 || index >= Items.Count)
1239 throw new ArgumentOutOfRangeException ("index");
1241 if (draw_mode == DrawMode.OwnerDrawVariable)
1242 item_heights.Remove (Items [index]);
1246 protected override void RefreshItems ()
1248 for (int i = 0; i < Items.Count; i++) {
1255 if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1256 SetControlText (GetItemText (Items [selected_index]), false);
1259 public override void ResetText ()
1261 Text = String.Empty;
1264 protected override bool ProcessKeyEventArgs (ref Message m)
1266 return base.ProcessKeyEventArgs (ref m);
1269 [EditorBrowsable (EditorBrowsableState.Advanced)]
1270 protected override void OnKeyDown (KeyEventArgs e)
1275 [EditorBrowsable (EditorBrowsableState.Advanced)]
1276 protected override void OnValidating (CancelEventArgs e)
1278 base.OnValidating (e);
1281 [EditorBrowsable (EditorBrowsableState.Advanced)]
1282 protected override void OnTextChanged (EventArgs e)
1284 base.OnTextChanged (e);
1288 protected virtual void OnTextUpdate (EventArgs e)
1290 EventHandler eh = (EventHandler) Events [TextUpdateEvent];
1295 protected override void OnMouseLeave (EventArgs e)
1298 if (flat_style == FlatStyle.Popup)
1301 base.OnMouseLeave (e);
1304 protected override void OnMouseEnter (EventArgs e)
1307 if (flat_style == FlatStyle.Popup)
1310 base.OnMouseEnter (e);
1315 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
1317 base.ScaleControl (factor, specified);
1321 public void Select (int start, int length)
1324 throw new ArgumentException ("Start cannot be less than zero");
1327 throw new ArgumentException ("length cannot be less than zero");
1329 if (dropdown_style == ComboBoxStyle.DropDownList)
1332 textbox_ctrl.Select (start, length);
1335 public void SelectAll ()
1337 if (dropdown_style == ComboBoxStyle.DropDownList)
1340 if (textbox_ctrl != null) {
1341 textbox_ctrl.ShowSelection = true;
1342 textbox_ctrl.SelectAll ();
1346 protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified)
1348 bool vertically_anchored = (Anchor & AnchorStyles.Top) != 0 && (Anchor & AnchorStyles.Bottom) != 0;
1349 bool vertically_docked = Dock == DockStyle.Left || Dock == DockStyle.Right || Dock == DockStyle.Fill;
1351 if ((specified & BoundsSpecified.Height) != 0 ||
1352 (specified == BoundsSpecified.None && (vertically_anchored || vertically_docked))) {
1354 requested_height = height;
1355 height = SnapHeight (height);
1358 base.SetBoundsCore (x, y, width, height, specified);
1361 protected override void SetItemCore (int index, object value)
1363 if (index < 0 || index >= Items.Count)
1366 Items[index] = value;
1369 protected override void SetItemsCore (IList value)
1374 Items.AddRange (value);
1380 public override string ToString ()
1382 return base.ToString () + ", Items.Count:" + Items.Count;
1385 protected override void WndProc (ref Message m)
1387 switch ((Msg) m.Msg) {
1389 case Msg.WM_KEYDOWN:
1390 Keys keys = (Keys) m.WParam.ToInt32 ();
1392 // Don't pass the message to base if auto complete is being used and available.
1393 if (textbox_ctrl != null && textbox_ctrl.CanNavigateAutoCompleteList) {
1394 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1398 if (keys == Keys.Up || keys == Keys.Down)
1400 goto case Msg.WM_CHAR;
1402 if (textbox_ctrl != null)
1403 XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1405 case Msg.WM_MOUSELEAVE:
1406 Point location = PointToClient (Control.MousePosition);
1407 if (ClientRectangle.Contains (location))
1413 base.WndProc (ref m);
1416 #endregion Public Methods
1418 #region Private Methods
1420 void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) {
1421 if(auto_complete_source == AutoCompleteSource.CustomSource) {
1422 //FIXME: handle add, remove and refresh events in AutoComplete algorithm.
1427 internal override bool InternalCapture {
1428 get { return Capture; }
1432 void LayoutComboBox ()
1434 int border = ThemeEngine.Current.Border3DSize.Width;
1436 text_area = ClientRectangle;
1437 text_area.Height = PreferredHeight;
1439 listbox_area = ClientRectangle;
1440 listbox_area.Y = text_area.Bottom + 3;
1441 listbox_area.Height -= (text_area.Height + 2);
1443 Rectangle prev_button_area = button_area;
1445 if (DropDownStyle == ComboBoxStyle.Simple)
1446 button_area = Rectangle.Empty;
1448 button_area = text_area;
1449 button_area.X = text_area.Right - button_width - border;
1450 button_area.Y = text_area.Y + border;
1451 button_area.Width = button_width;
1452 button_area.Height = text_area.Height - 2 * border;
1454 if (flat_style == FlatStyle.Popup || flat_style == FlatStyle.Flat) {
1455 button_area.Inflate (1, 1);
1457 button_area.Width -= 2;
1462 if (button_area != prev_button_area) {
1463 prev_button_area.Y -= border;
1464 prev_button_area.Width += border;
1465 prev_button_area.Height += 2 * border;
1466 Invalidate (prev_button_area);
1467 Invalidate (button_area);
1470 if (textbox_ctrl != null) {
1471 int text_border = border + 1;
1472 textbox_ctrl.Location = new Point (text_area.X + text_border, text_area.Y + text_border);
1473 textbox_ctrl.Width = text_area.Width - button_area.Width - text_border * 2;
1474 textbox_ctrl.Height = text_area.Height - text_border * 2;
1477 if (listbox_ctrl != null && dropdown_style == ComboBoxStyle.Simple) {
1478 listbox_ctrl.Location = listbox_area.Location;
1479 listbox_ctrl.CalcListBoxArea ();
1483 private void CreateComboListBox ()
1485 listbox_ctrl = new ComboListBox (this);
1486 listbox_ctrl.HighlightedIndex = SelectedIndex;
1489 internal void Draw (Rectangle clip, Graphics dc)
1491 Theme theme = ThemeEngine.Current;
1492 FlatStyle style = FlatStyle.Standard;
1493 bool is_flat = false;
1496 style = this.FlatStyle;
1497 is_flat = style == FlatStyle.Flat || style == FlatStyle.Popup;
1500 theme.ComboBoxDrawBackground (this, dc, clip, style);
1502 int border = theme.Border3DSize.Width;
1504 // No edit control, we paint the edit ourselves
1505 if (dropdown_style == ComboBoxStyle.DropDownList) {
1506 DrawItemState state = DrawItemState.None;
1507 Rectangle item_rect = text_area;
1508 item_rect.X += border;
1509 item_rect.Y += border;
1510 item_rect.Width -= (button_area.Width + 2 * border);
1511 item_rect.Height -= 2 * border;
1514 state = DrawItemState.Selected;
1515 state |= DrawItemState.Focus;
1518 state |= DrawItemState.ComboBoxEdit;
1519 OnDrawItem (new DrawItemEventArgs (dc, Font, item_rect, SelectedIndex, state, ForeColor, BackColor));
1522 if (show_dropdown_button) {
1523 ButtonState current_state;
1525 current_state = button_state;
1527 current_state = ButtonState.Inactive;
1529 if (is_flat || theme.ComboBoxNormalDropDownButtonHasTransparentBackground (this, current_state))
1530 dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), button_area);
1533 theme.DrawFlatStyleComboButton (dc, button_area, current_state);
1535 theme.ComboBoxDrawNormalDropDownButton (this, dc, clip, button_area, current_state);
1540 internal bool DropDownButtonEntered {
1541 get { return drop_down_button_entered; }
1543 if (drop_down_button_entered == value)
1545 drop_down_button_entered = value;
1546 if (ThemeEngine.Current.ComboBoxDropDownButtonHasHotElementStyle (this))
1547 Invalidate (button_area);
1551 internal void DropDownListBox ()
1553 DropDownButtonEntered = false;
1555 if (DropDownStyle == ComboBoxStyle.Simple)
1558 if (listbox_ctrl == null)
1559 CreateComboListBox ();
1561 listbox_ctrl.Location = PointToScreen (new Point (text_area.X, text_area.Y + text_area.Height));
1563 FindMatchOrSetIndex(SelectedIndex);
1566 if (textbox_ctrl != null)
1567 textbox_ctrl.HideAutoCompleteList ();
1570 if (listbox_ctrl.ShowWindow ())
1571 dropped_down = true;
1573 button_state = ButtonState.Pushed;
1574 if (dropdown_style == ComboBoxStyle.DropDownList)
1575 Invalidate (text_area);
1578 internal void DropDownListBoxFinished ()
1580 if (DropDownStyle == ComboBoxStyle.Simple)
1583 FindMatchOrSetIndex (SelectedIndex);
1584 button_state = ButtonState.Normal;
1585 Invalidate (button_area);
1586 dropped_down = false;
1588 OnDropDownClosed (EventArgs.Empty);
1591 * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
1592 * this causes the popup to appear under the main form. This is horrible but necessary
1595 // If the user opens a new form in an event, it will close our dropdown,
1596 // so we need a null check here
1597 if (listbox_ctrl != null) {
1598 listbox_ctrl.Dispose ();
1599 listbox_ctrl = null;
1603 private int FindStringCaseInsensitive (string search)
1605 if (search.Length == 0) {
1609 for (int i = 0; i < Items.Count; i++)
1611 if (String.Compare (GetItemText (Items[i]), 0, search, 0, search.Length, true) == 0)
1618 // Search in the list for the substring, starting the search at the list
1619 // position specified, the search wraps thus covering all the list.
1620 internal int FindStringCaseInsensitive (string search, int start_index)
1622 if (search.Length == 0) {
1625 // Accept from first item to after last item. i.e. all cases of (SelectedIndex+1).
1626 if (start_index < 0 || start_index > Items.Count)
1627 throw new ArgumentOutOfRangeException("start_index");
1629 for (int i = 0; i < Items.Count; i++) {
1630 int index = (i + start_index) % Items.Count;
1631 if (String.Compare (GetItemText (Items [index]), 0, search, 0, search.Length, true) == 0)
1638 internal override bool IsInputCharInternal (char charCode)
1643 internal override ContextMenu ContextMenuInternal {
1645 return base.ContextMenuInternal;
1648 base.ContextMenuInternal = value;
1649 if (textbox_ctrl != null) {
1650 textbox_ctrl.ContextMenu = value;
1655 internal void RestoreContextMenu ()
1657 textbox_ctrl.RestoreContextMenu ();
1660 private void OnKeyDownCB(object sender, KeyEventArgs e)
1662 if (Items.Count == 0)
1669 FindMatchOrSetIndex(Math.Max(SelectedIndex - 1, 0));
1672 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1673 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1677 if ((e.Modifiers & Keys.Alt) == Keys.Alt)
1680 FindMatchOrSetIndex(Math.Min(SelectedIndex + 1, Items.Count - 1));
1683 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1684 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1688 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1692 SelectedIndex = Math.Max (SelectedIndex - offset, 0);
1695 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1696 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1700 if (SelectedIndex == -1) {
1702 if (dropdown_style != ComboBoxStyle.Simple)
1706 offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1710 SelectedIndex = Math.Min (SelectedIndex + offset, Items.Count - 1);
1713 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1714 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1719 DropDownListBoxFinished ();
1723 if (dropdown_style == ComboBoxStyle.DropDownList) {
1727 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1728 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1733 if (dropdown_style == ComboBoxStyle.DropDownList) {
1734 SelectedIndex = Items.Count - 1;
1737 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1738 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1747 // If no item is currently selected, and an item is found matching the text
1748 // in the textbox, then selected that item. Otherwise the item at the given
1749 // index is selected.
1750 private void FindMatchOrSetIndex(int index)
1753 if (SelectedIndex == -1 && Text.Length != 0)
1754 match = FindStringCaseInsensitive(Text);
1756 SelectedIndex = match;
1758 SelectedIndex = index;
1761 void OnMouseDownCB (object sender, MouseEventArgs e)
1764 if (DropDownStyle == ComboBoxStyle.DropDownList)
1765 area = ClientRectangle;
1769 if (area.Contains (e.X, e.Y)) {
1770 if (Items.Count > 0)
1773 button_state = ButtonState.Pushed;
1774 OnDropDown (EventArgs.Empty);
1777 Invalidate (button_area);
1783 void OnMouseEnter (object sender, EventArgs e)
1785 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this))
1789 void OnMouseLeave (object sender, EventArgs e)
1791 if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this)) {
1792 drop_down_button_entered = false;
1795 if (show_dropdown_button)
1796 DropDownButtonEntered = false;
1800 void OnMouseMoveCB (object sender, MouseEventArgs e)
1802 if (show_dropdown_button && !dropped_down)
1803 DropDownButtonEntered = button_area.Contains (e.Location);
1805 if (DropDownStyle == ComboBoxStyle.Simple)
1808 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1809 Point location = listbox_ctrl.PointToClient (Control.MousePosition);
1810 if (listbox_ctrl.ClientRectangle.Contains (location))
1811 listbox_ctrl.Capture = true;
1815 void OnMouseUpCB (object sender, MouseEventArgs e)
1819 button_state = ButtonState.Normal;
1820 Invalidate (button_area);
1822 OnClick (EventArgs.Empty);
1825 listbox_ctrl.Capture = true;
1828 private void OnMouseWheelCB (object sender, MouseEventArgs me)
1830 if (Items.Count == 0)
1833 if (listbox_ctrl != null && listbox_ctrl.Visible) {
1834 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
1835 listbox_ctrl.Scroll (-lines);
1837 int lines = me.Delta / 120;
1838 int index = SelectedIndex - lines;
1841 else if (index >= Items.Count)
1842 index = Items.Count - 1;
1843 SelectedIndex = index;
1847 internal override void OnPaintInternal (PaintEventArgs pevent)
1849 if (suspend_ctrlupdate)
1852 Draw (ClientRectangle, pevent.Graphics);
1855 private void OnTextBoxClick (object sender, EventArgs e)
1860 private void OnTextChangedEdit (object sender, EventArgs e)
1862 if (process_textchanged_event == false)
1865 int item = FindStringCaseInsensitive (textbox_ctrl.Text);
1868 // Setting base.Text below will raise this event
1869 // if we found something
1870 OnTextChanged (EventArgs.Empty);
1874 // TODO: THIS IS BROKEN-ISH
1875 // I don't think we should hilight, and setting the top item does weirdness
1876 // when there is no scrollbar
1878 if (listbox_ctrl != null) {
1879 listbox_ctrl.SetTopItem (item);
1880 listbox_ctrl.HighlightedIndex = item;
1883 base.Text = textbox_ctrl.Text;
1886 private void OnTextKeyPress (object sender, KeyPressEventArgs e)
1888 selected_index = -1;
1891 internal void SetControlText (string s, bool suppressTextChanged)
1893 if (suppressTextChanged)
1894 process_textchanged_event = false;
1896 textbox_ctrl.Text = s;
1897 textbox_ctrl.SelectAll ();
1898 process_textchanged_event = true;
1901 void UpdateComboBoxBounds ()
1903 if (requested_height == -1)
1906 // Save the requested height since set bounds can destroy it
1907 int save_height = requested_height;
1908 SetBounds (bounds.X, bounds.Y, bounds.Width, SnapHeight (requested_height),
1909 BoundsSpecified.Height);
1910 requested_height = save_height;
1913 int SnapHeight (int height)
1915 if (DropDownStyle == ComboBoxStyle.Simple && height > PreferredHeight) {
1916 if (IntegralHeight) {
1917 int border = ThemeEngine.Current.Border3DSize.Height;
1918 int lb_height = (height - PreferredHeight - 2) - border * 2;
1919 if (lb_height > ItemHeight) {
1920 int partial = (lb_height) % ItemHeight;
1922 } else if (lb_height < ItemHeight)
1923 height = PreferredHeight;
1926 height = PreferredHeight;
1931 private void UpdatedItems ()
1933 if (listbox_ctrl != null) {
1934 listbox_ctrl.UpdateLastVisibleItem ();
1935 listbox_ctrl.CalcListBoxArea ();
1936 listbox_ctrl.Refresh ();
1940 #endregion Private Methods
1942 [ListBindableAttribute (false)]
1943 public class ObjectCollection : IList, ICollection, IEnumerable
1946 private ComboBox owner;
1947 internal ArrayList object_items = new ArrayList ();
1949 #region UIA Framework Events
1953 // We are using Reflection to add/remove internal events.
1954 // Class ListProvider uses the events.
1956 //Event used to generate UIA StructureChangedEvent
1957 static object UIACollectionChangedEvent = new object ();
1959 internal event CollectionChangeEventHandler UIACollectionChanged {
1960 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
1961 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
1964 internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
1966 CollectionChangeEventHandler eh
1967 = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
1973 #endregion UIA Framework Events
1975 public ObjectCollection (ComboBox owner)
1980 #region Public Properties
1982 get { return object_items.Count; }
1985 public bool IsReadOnly {
1986 get { return false; }
1990 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1991 public virtual object this [int index] {
1993 if (index < 0 || index >= Count)
1994 throw new ArgumentOutOfRangeException ("index");
1996 return object_items[index];
1999 if (index < 0 || index >= Count)
2000 throw new ArgumentOutOfRangeException ("index");
2002 throw new ArgumentNullException ("value");
2005 //UIA Framework event: Item Removed
2006 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, object_items [index]));
2009 object_items[index] = value;
2012 //UIA Framework event: Item Added
2013 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, value));
2016 if (owner.listbox_ctrl != null)
2017 owner.listbox_ctrl.InvalidateItem (index);
2018 if (index == owner.SelectedIndex) {
2019 if (owner.textbox_ctrl == null)
2022 owner.textbox_ctrl.SelectedText = value.ToString ();
2027 bool ICollection.IsSynchronized {
2028 get { return false; }
2031 object ICollection.SyncRoot {
2032 get { return this; }
2035 bool IList.IsFixedSize {
2036 get { return false; }
2039 #endregion Public Properties
2041 #region Public Methods
2042 public int Add (object item)
2046 idx = AddItem (item);
2047 owner.UpdatedItems ();
2051 public void AddRange (object[] items)
2054 throw new ArgumentNullException ("items");
2056 foreach (object mi in items)
2059 owner.UpdatedItems ();
2062 public void Clear ()
2064 owner.selected_index = -1;
2065 object_items.Clear ();
2066 owner.UpdatedItems ();
2070 //UIA Framework event: Items list cleared
2071 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, null));
2075 public bool Contains (object value)
2078 throw new ArgumentNullException ("value");
2080 return object_items.Contains (value);
2084 public void CopyTo (object [] destination, int arrayIndex)
2086 object_items.CopyTo (destination, arrayIndex);
2089 void ICollection.CopyTo (Array destination, int index)
2091 object_items.CopyTo (destination, index);
2094 public void CopyTo (object [] dest, int arrayIndex)
2096 object_items.CopyTo (dest, arrayIndex);
2099 void ICollection.CopyTo (Array dest, int index)
2101 object_items.CopyTo (dest, index);
2105 public IEnumerator GetEnumerator ()
2107 return object_items.GetEnumerator ();
2110 int IList.Add (object item)
2115 public int IndexOf (object value)
2118 throw new ArgumentNullException ("value");
2120 return object_items.IndexOf (value);
2123 public void Insert (int index, object item)
2125 if (index < 0 || index > Count)
2126 throw new ArgumentOutOfRangeException ("index");
2128 throw new ArgumentNullException ("item");
2130 owner.BeginUpdate ();
2135 object_items.Insert (index, item);
2137 //UIA Framework event: Item added
2138 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2142 owner.EndUpdate (); // Calls UpdatedItems
2145 public void Remove (object value)
2150 if (IndexOf (value) == owner.SelectedIndex)
2151 owner.SelectedIndex = -1;
2153 RemoveAt (IndexOf (value));
2156 public void RemoveAt (int index)
2158 if (index < 0 || index >= Count)
2159 throw new ArgumentOutOfRangeException ("index");
2161 if (index == owner.SelectedIndex)
2162 owner.SelectedIndex = -1;
2165 object removed = object_items [index];
2169 object_items.RemoveAt (index);
2170 owner.UpdatedItems ();
2173 //UIA Framework event: Item removed
2174 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, removed));
2177 #endregion Public Methods
2179 #region Private Methods
2180 private int AddItem (object item)
2183 throw new ArgumentNullException ("item");
2187 foreach (object o in object_items) {
2188 if (String.Compare (item.ToString (), o.ToString ()) < 0) {
2189 object_items.Insert (index, item);
2191 // If we added the new item before the selectedindex
2192 // bump the selectedindex by one, behavior differs if
2193 // Handle has not been created.
2194 if (index <= owner.selected_index && owner.IsHandleCreated)
2195 owner.selected_index++;
2198 //UIA Framework event: Item added
2199 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2207 object_items.Add (item);
2210 //UIA Framework event: Item added
2211 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2214 return object_items.Count - 1;
2217 internal void AddRange (IList items)
2219 foreach (object mi in items)
2222 owner.UpdatedItems ();
2225 internal void Sort ()
2227 // If the objects the user put here don't have their own comparer,
2228 // use one that compares based on the object's ToString
2229 if (object_items.Count > 0 && object_items[0] is IComparer)
2230 object_items.Sort ();
2232 object_items.Sort (new ObjectComparer (owner));
2235 private class ObjectComparer : IComparer
2237 private ListControl owner;
2239 public ObjectComparer (ListControl owner)
2244 #region IComparer Members
2245 public int Compare (object x, object y)
2247 return string.Compare (owner.GetItemText (x), owner.GetItemText (y));
2251 #endregion Private Methods
2254 internal class ComboTextBox : TextBox {
2256 private ComboBox owner;
2258 public ComboTextBox (ComboBox owner)
2261 ShowSelection = false;
2262 HideSelection = false;
2265 internal void SetSelectable (bool selectable)
2267 SetStyle (ControlStyles.Selectable, selectable);
2270 internal void ActivateCaret (bool active)
2273 document.CaretHasFocus ();
2275 document.CaretLostFocus ();
2279 internal override void OnTextUpdate ()
2281 base.OnTextUpdate ();
2282 owner.OnTextUpdate (EventArgs.Empty);
2286 protected override void OnGotFocus (EventArgs e)
2288 owner.Select (false, true);
2291 protected override void OnLostFocus (EventArgs e)
2293 owner.Select (false, true);
2296 public override bool Focused {
2298 return owner.Focused;
2302 internal override bool ActivateOnShow { get { return false; } }
2305 internal class ComboListBox : Control
2307 private ComboBox owner;
2308 private VScrollBarLB vscrollbar_ctrl;
2309 private int top_item; /* First item that we show the in the current page */
2310 private int last_item; /* Last visible item */
2311 internal int page_size; /* Number of listbox items per page */
2312 private Rectangle textarea_drawable; /* Rectangle of the drawable text area */
2314 internal enum ItemNavigation
2324 class VScrollBarLB : VScrollBar
2326 public VScrollBarLB ()
2330 internal override bool InternalCapture {
2331 get { return Capture; }
2335 public void FireMouseDown (MouseEventArgs e)
2340 e = TranslateEvent (e);
2344 public void FireMouseUp (MouseEventArgs e)
2349 e = TranslateEvent (e);
2353 public void FireMouseMove (MouseEventArgs e)
2358 e = TranslateEvent (e);
2362 MouseEventArgs TranslateEvent (MouseEventArgs e)
2364 Point loc = PointToClient (Control.MousePosition);
2365 return new MouseEventArgs (e.Button, e.Clicks, loc.X, loc.Y, e.Delta);
2369 public ComboListBox (ComboBox owner)
2376 MouseWheel += new MouseEventHandler (OnMouseWheelCLB);
2378 SetStyle (ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
2379 SetStyle (ControlStyles.ResizeRedraw | ControlStyles.Opaque, true);
2381 this.is_visible = false;
2383 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2384 InternalBorderStyle = BorderStyle.Fixed3D;
2386 InternalBorderStyle = BorderStyle.FixedSingle;
2389 protected override CreateParams CreateParams
2392 CreateParams cp = base.CreateParams;
2393 if (owner == null || owner.DropDownStyle == ComboBoxStyle.Simple)
2396 cp.Style ^= (int)WindowStyles.WS_CHILD;
2397 cp.Style ^= (int)WindowStyles.WS_VISIBLE;
2398 cp.Style |= (int)WindowStyles.WS_POPUP;
2399 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW | (int) WindowExStyles.WS_EX_TOPMOST;
2404 internal override bool InternalCapture {
2413 internal override bool ActivateOnShow { get { return false; } }
2414 #region Private Methods
2416 // Calcs the listbox area
2417 internal void CalcListBoxArea ()
2420 bool show_scrollbar = false;
2422 if (owner.DropDownStyle == ComboBoxStyle.Simple) {
2423 Rectangle area = owner.listbox_area;
2425 height = area.Height;
2427 // No calculation needed
2428 if (height <= 0 || width <= 0)
2431 else { // DropDown or DropDownList
2433 width = owner.DropDownWidth;
2434 int count = (owner.Items.Count <= owner.MaxDropDownItems) ? owner.Items.Count : owner.MaxDropDownItems;
2436 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2438 for (int i = 0; i < count; i++) {
2439 height += owner.GetItemHeight (i);
2444 height = owner.DropDownHeight;
2446 height = owner.ItemHeight * count;
2451 page_size = Math.Max (height / owner.ItemHeight, 1);
2453 ComboBoxStyle dropdown_style = owner.DropDownStyle;
2454 if ((dropdown_style != ComboBoxStyle.Simple && owner.Items.Count <= owner.MaxDropDownItems)
2455 || (dropdown_style == ComboBoxStyle.Simple && owner.Items.Count * owner.ItemHeight < height)) {
2457 if (vscrollbar_ctrl != null)
2458 vscrollbar_ctrl.Visible = false;
2459 if (dropdown_style != ComboBoxStyle.Simple)
2460 height = owner.ItemHeight * owner.items.Count;
2462 /* Need vertical scrollbar */
2463 if (vscrollbar_ctrl == null) {
2464 vscrollbar_ctrl = new VScrollBarLB ();
2465 vscrollbar_ctrl.Minimum = 0;
2466 vscrollbar_ctrl.SmallChange = 1;
2467 vscrollbar_ctrl.LargeChange = 1;
2468 vscrollbar_ctrl.Maximum = 0;
2469 vscrollbar_ctrl.ValueChanged += new EventHandler (VerticalScrollEvent);
2470 Controls.AddImplicit (vscrollbar_ctrl);
2473 vscrollbar_ctrl.Dock = DockStyle.Right;
2475 vscrollbar_ctrl.Maximum = owner.Items.Count - 1;
2477 int large = page_size;
2479 int large = (dropdown_style == ComboBoxStyle.Simple ? page_size : owner.maxdrop_items) - 1;
2483 vscrollbar_ctrl.LargeChange = large;
2484 show_scrollbar = vscrollbar_ctrl.Visible = true;
2486 int hli = HighlightedIndex;
2488 hli = Math.Min (hli, vscrollbar_ctrl.Maximum);
2489 vscrollbar_ctrl.Value = hli;
2493 Size = new Size (width, height);
2494 textarea_drawable = ClientRectangle;
2495 textarea_drawable.Width = width;
2496 textarea_drawable.Height = height;
2498 if (vscrollbar_ctrl != null && show_scrollbar)
2499 textarea_drawable.Width -= vscrollbar_ctrl.Width;
2501 last_item = LastVisibleItem ();
2504 private void Draw (Rectangle clip, Graphics dc)
2506 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (owner.BackColor), clip);
2508 if (owner.Items.Count > 0) {
2510 for (int i = top_item; i <= last_item; i++) {
2511 Rectangle item_rect = GetItemDisplayRectangle (i, top_item);
2513 if (!clip.IntersectsWith (item_rect))
2516 DrawItemState state = DrawItemState.None;
2518 if (i == HighlightedIndex) {
2519 state |= DrawItemState.Selected;
2521 if (owner.DropDownStyle == ComboBoxStyle.DropDownList) {
2522 state |= DrawItemState.Focus;
2526 owner.OnDrawItem (new DrawItemEventArgs (dc, owner.Font, item_rect,
2527 i, state, owner.ForeColor, owner.BackColor));
2532 int highlighted_index = -1;
2534 public int HighlightedIndex {
2535 get { return highlighted_index; }
2537 if (highlighted_index == value)
2540 if (highlighted_index != -1 && highlighted_index < this.owner.Items.Count)
2541 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2542 highlighted_index = value;
2543 if (highlighted_index != -1)
2544 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2548 private Rectangle GetItemDisplayRectangle (int index, int top_index)
2550 if (index < 0 || index >= owner.Items.Count)
2551 throw new ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
2553 Rectangle item_rect = new Rectangle ();
2554 int height = owner.GetItemHeight (index);
2557 item_rect.Width = textarea_drawable.Width;
2558 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2560 for (int i = top_index; i < index; i++)
2561 item_rect.Y += owner.GetItemHeight (i);
2563 item_rect.Y = height * (index - top_index);
2565 item_rect.Height = height;
2569 public void HideWindow ()
2571 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2576 owner.DropDownListBoxFinished ();
2579 private int IndexFromPointDisplayRectangle (int x, int y)
2581 for (int i = top_item; i <= last_item; i++) {
2582 if (GetItemDisplayRectangle (i, top_item).Contains (x, y) == true)
2589 public void InvalidateItem (int index)
2592 Invalidate (GetItemDisplayRectangle (index, top_item));
2595 public int LastVisibleItem ()
2597 Rectangle item_rect;
2598 int top_y = textarea_drawable.Y + textarea_drawable.Height;
2601 for (i = top_item; i < owner.Items.Count; i++) {
2602 item_rect = GetItemDisplayRectangle (i, top_item);
2603 if (item_rect.Y + item_rect.Height > top_y) {
2610 public void SetTopItem (int item)
2612 if (top_item == item)
2615 UpdateLastVisibleItem ();
2619 public int FirstVisibleItem ()
2624 bool scrollbar_grabbed = false;
2628 if (vscrollbar_ctrl == null || !vscrollbar_ctrl.is_visible)
2631 return vscrollbar_ctrl.Bounds.Contains (PointToClient (Control.MousePosition));
2635 protected override void OnMouseDown (MouseEventArgs e)
2638 vscrollbar_ctrl.FireMouseDown (e);
2639 scrollbar_grabbed = true;
2643 protected override void OnMouseMove (MouseEventArgs e)
2645 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2648 if (scrollbar_grabbed || (!Capture && InScrollBar)) {
2649 vscrollbar_ctrl.FireMouseMove (e);
2653 Point pt = PointToClient (Control.MousePosition);
2654 int index = IndexFromPointDisplayRectangle (pt.X, pt.Y);
2657 HighlightedIndex = index;
2660 protected override void OnMouseUp (MouseEventArgs e)
2662 int index = IndexFromPointDisplayRectangle (e.X, e.Y);
2664 if (scrollbar_grabbed) {
2665 vscrollbar_ctrl.FireMouseUp (e);
2666 scrollbar_grabbed = false;
2668 HighlightedIndex = index;
2677 bool is_change = owner.SelectedIndex != index;
2679 owner.SelectedIndex = index;
2680 owner.OnSelectionChangeCommitted (new EventArgs ());
2682 // If the user selected the already selected item, SelectedIndex
2683 // won't fire these events, but .Net does, so we do it here
2685 owner.OnSelectedValueChanged (EventArgs.Empty);
2686 owner.OnSelectedIndexChanged (EventArgs.Empty);
2692 internal override void OnPaintInternal (PaintEventArgs pevent)
2694 Draw (pevent.ClipRectangle,pevent.Graphics);
2697 public bool ShowWindow ()
2699 if (owner.DropDownStyle == ComboBoxStyle.Simple && owner.Items.Count == 0)
2702 HighlightedIndex = owner.SelectedIndex;
2708 owner.OnDropDown (EventArgs.Empty);
2712 public void UpdateLastVisibleItem ()
2714 last_item = LastVisibleItem ();
2717 public void Scroll (int delta)
2719 if (delta == 0 || vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2722 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2724 int val = vscrollbar_ctrl.Value + delta;
2727 else if (val < vscrollbar_ctrl.Minimum)
2728 val = vscrollbar_ctrl.Minimum;
2729 vscrollbar_ctrl.Value = val;
2732 private void OnMouseWheelCLB (object sender, MouseEventArgs me)
2734 if (owner.Items.Count == 0)
2737 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
2742 private void VerticalScrollEvent (object sender, EventArgs e)
2744 if (top_item == vscrollbar_ctrl.Value)
2747 top_item = vscrollbar_ctrl.Value;
2748 UpdateLastVisibleItem ();
2752 protected override void WndProc(ref Message m) {
2753 if (m.Msg == (int)Msg.WM_SETFOCUS) {
2754 owner.Select (false, true);
2756 base.WndProc (ref m);
2759 #endregion Private Methods