2008-09-08 Jonathan Pobst <monkey@jpobst.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / ComboBox.cs
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:
8 //
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 //
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.
19 //
20 // Copyright (c) 2004-2006 Novell, Inc.
21 //
22 // Authors:
23 //      Jordi Mas i Hernandez, jordi@ximian.com
24 //      Mike Kestner  <mkestner@novell.com>
25 //      Daniel Nauck    (dna(at)mono-project(dot)de)
26
27 using System;
28 using System.Collections;
29 using System.ComponentModel;
30 using System.ComponentModel.Design;
31 using System.ComponentModel.Design.Serialization;
32 using System.Drawing;
33 using System.Globalization;
34 using System.Reflection;
35 using System.Runtime.InteropServices;
36
37 namespace System.Windows.Forms
38 {
39         [DefaultProperty("Items")]
40         [DefaultEvent("SelectedIndexChanged")]
41         [Designer ("System.Windows.Forms.Design.ComboBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
42 #if NET_2_0
43         [DefaultBindingProperty ("Text")]
44         [ClassInterface (ClassInterfaceType.AutoDispatch)]
45         [ComVisible(true)]
46 #endif
47         public class ComboBox : ListControl
48         {
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;
57                 private bool sorted;
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;
74 #if NET_2_0
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;
80 #endif
81
82                 [ComVisible(true)]
83                 public class ChildAccessibleObject : AccessibleObject {
84
85                         public ChildAccessibleObject (ComboBox owner, IntPtr handle)
86                                 : base (owner)
87                         {
88                         }
89
90                         public override string Name {
91                                 get {
92                                         return base.Name;
93                                 }
94                         }
95                 }
96
97                 public ComboBox ()
98                 {
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;
104
105 #if NET_2_0
106                         drop_down_height = 106;
107                         flat_style = FlatStyle.Standard;
108 #endif
109
110                         /* Events */
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);
118                 }
119
120                 #region events
121                 
122                 [Browsable (false)]
123                 [EditorBrowsable (EditorBrowsableState.Never)]
124                 public new event EventHandler BackgroundImageChanged {
125                         add { base.BackgroundImageChanged += value; }
126                         remove { base.BackgroundImageChanged -= value; }
127                 }
128                 
129 #if NET_2_0
130
131                 [Browsable (false)]
132                 [EditorBrowsable (EditorBrowsableState.Never)]
133                 public new event EventHandler BackgroundImageLayoutChanged
134                 {
135                         add { base.BackgroundImageLayoutChanged += value; }
136                         remove { base.BackgroundImageLayoutChanged -= value; }
137                 }
138
139                 [Browsable (false)]
140                 [EditorBrowsable (EditorBrowsableState.Never)]
141                 public new event EventHandler DoubleClick
142                 {
143                         add { base.DoubleClick += value; }
144                         remove { base.DoubleClick -= value; }
145                 }
146 #endif
147
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 ();
154 #if NET_2_0
155                 static object DropDownClosedEvent = new object ();
156                 static object TextUpdateEvent = new object ();
157 #endif
158
159                 public event DrawItemEventHandler DrawItem {
160                         add { Events.AddHandler (DrawItemEvent, value); }
161                         remove { Events.RemoveHandler (DrawItemEvent, value); }
162                 }
163
164                 public event EventHandler DropDown {
165                         add { Events.AddHandler (DropDownEvent, value); }
166                         remove { Events.RemoveHandler (DropDownEvent, value); }
167                 }
168 #if NET_2_0
169                 public event EventHandler DropDownClosed
170                 {
171                         add { Events.AddHandler (DropDownClosedEvent, value); }
172                         remove { Events.RemoveHandler (DropDownClosedEvent, value); }
173                 }
174 #endif
175
176                 public event EventHandler DropDownStyleChanged {
177                         add { Events.AddHandler (DropDownStyleChangedEvent, value); }
178                         remove { Events.RemoveHandler (DropDownStyleChangedEvent, value); }
179                 }
180
181                 public event MeasureItemEventHandler MeasureItem {
182                         add { Events.AddHandler (MeasureItemEvent, value); }
183                         remove { Events.RemoveHandler (MeasureItemEvent, value); }
184                 }
185 #if NET_2_0
186                 [Browsable (false)]
187                 [EditorBrowsable (EditorBrowsableState.Never)]
188                 public new event EventHandler PaddingChanged
189                 {
190                         add { base.PaddingChanged += value; }
191                         remove { base.PaddingChanged -= value; }
192                 }
193 #endif
194                 
195                 [Browsable (false)]
196                 [EditorBrowsable (EditorBrowsableState.Never)]
197                 public new event PaintEventHandler Paint {
198                         add { base.Paint += value; }
199                         remove { base.Paint -= value; }
200                 }
201                 
202                 public event EventHandler SelectedIndexChanged {
203                         add { Events.AddHandler (SelectedIndexChangedEvent, value); }
204                         remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
205                 }
206
207                 public event EventHandler SelectionChangeCommitted {
208                         add { Events.AddHandler (SelectionChangeCommittedEvent, value); }
209                         remove { Events.RemoveHandler (SelectionChangeCommittedEvent, value); }
210                 }
211 #if NET_2_0
212                 public event EventHandler TextUpdate
213                 {
214                         add { Events.AddHandler (TextUpdateEvent, value); }
215                         remove { Events.RemoveHandler (TextUpdateEvent, value); }
216                 }
217 #endif
218
219                 #endregion Events
220
221                 #region Public Properties
222 #if NET_2_0
223                 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
224                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
225                 [Browsable (true)]
226                 [EditorBrowsable (EditorBrowsableState.Always)]
227                 [Localizable (true)]
228                 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design,
229                          "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
230                 public AutoCompleteStringCollection AutoCompleteCustomSource { 
231                         get {
232                                 if(auto_complete_custom_source == null) {
233                                         auto_complete_custom_source = new AutoCompleteStringCollection ();
234                                         auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
235                                 }
236                                 return auto_complete_custom_source;
237                         }
238                         set {
239                                 if(auto_complete_custom_source == value)
240                                         return;
241
242                                 if(auto_complete_custom_source != null) //remove eventhandler from old collection
243                                         auto_complete_custom_source.CollectionChanged -= new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
244
245                                 auto_complete_custom_source = value;
246
247                                 if(auto_complete_custom_source != null)
248                                         auto_complete_custom_source.CollectionChanged += new CollectionChangeEventHandler (OnAutoCompleteCustomSourceChanged);
249
250                                 SetTextBoxAutoCompleteData ();
251                         }
252                 }
253
254                 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
255                 [Browsable (true)]
256                 [EditorBrowsable (EditorBrowsableState.Always)]
257                 [DefaultValue (AutoCompleteMode.None)]
258                 public AutoCompleteMode AutoCompleteMode {
259                         get { return auto_complete_mode; }
260                         set {
261                                 if(auto_complete_mode == value)
262                                         return;
263
264                                 if((value < AutoCompleteMode.None) || (value > AutoCompleteMode.SuggestAppend))
265                                         throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteMode", value));
266
267                                 auto_complete_mode = value;
268                                 SetTextBoxAutoCompleteData ();
269                         }
270                 }
271
272                 [MonoTODO("AutoCompletion algorithm is currently not implemented.")]
273                 [Browsable (true)]
274                 [EditorBrowsable (EditorBrowsableState.Always)]
275                 [DefaultValue (AutoCompleteSource.None)]
276                 public AutoCompleteSource AutoCompleteSource {
277                         get { return auto_complete_source; }
278                         set {
279                                 if(auto_complete_source == value)
280                                         return;
281
282                                 if(!Enum.IsDefined (typeof (AutoCompleteSource), value))
283                                         throw new InvalidEnumArgumentException (Locale.GetText ("Enum argument value '{0}' is not valid for AutoCompleteSource", value));
284
285                                 auto_complete_source = value;
286                                 SetTextBoxAutoCompleteData ();
287                         }
288                 }
289
290                 void SetTextBoxAutoCompleteData ()
291                 {
292                         if (textbox_ctrl == null)
293                                 return;
294
295                         textbox_ctrl.AutoCompleteMode = auto_complete_mode;
296
297                         if (auto_complete_source == AutoCompleteSource.ListItems) {
298                                 textbox_ctrl.AutoCompleteSource = AutoCompleteSource.CustomSource;
299                                 textbox_ctrl.AutoCompleteCustomSource = null;
300                                 textbox_ctrl.AutoCompleteInternalSource = this;
301                         } else {
302                                 textbox_ctrl.AutoCompleteSource = auto_complete_source;
303                                 textbox_ctrl.AutoCompleteCustomSource = auto_complete_custom_source;
304                                 textbox_ctrl.AutoCompleteInternalSource = null;
305                         }
306                 }
307 #endif
308                 public override Color BackColor {
309                         get { return base.BackColor; }
310                         set {
311                                 if (base.BackColor == value)
312                                         return;
313                                 base.BackColor = value;
314                                 Refresh ();
315                         }
316                 }
317
318                 [Browsable (false)]
319                 [EditorBrowsable (EditorBrowsableState.Never)]
320                 public override Image BackgroundImage {
321                         get { return base.BackgroundImage; }
322                         set {
323                                 if (base.BackgroundImage == value)
324                                         return;
325                                 base.BackgroundImage = value;
326                                 Refresh ();
327                         }
328                 }
329
330 #if NET_2_0
331                 [Browsable (false)]
332                 [EditorBrowsable (EditorBrowsableState.Never)]
333                 public override ImageLayout BackgroundImageLayout {
334                         get { return base.BackgroundImageLayout; }
335                         set { base.BackgroundImageLayout = value; }
336                 }
337 #endif
338
339                 protected override CreateParams CreateParams {
340                         get { return base.CreateParams;}
341                 }
342
343 #if NET_2_0
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; }
351                 }
352 #endif
353
354                 protected override Size DefaultSize {
355                         get { return new Size (121, 21); }
356                 }
357
358                 [RefreshProperties(RefreshProperties.Repaint)]
359                 [DefaultValue (DrawMode.Normal)]
360                 [MWFCategory("Behavior")]
361                 public DrawMode DrawMode {
362                         get { return draw_mode; }
363                         set {
364                                 if (!Enum.IsDefined (typeof (DrawMode), value))
365                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for DrawMode", value));
366
367                                 if (draw_mode == value)
368                                         return;
369
370                                 if (draw_mode == DrawMode.OwnerDrawVariable)
371                                         item_heights = null;
372                                 draw_mode = value;
373                                 if (draw_mode == DrawMode.OwnerDrawVariable)
374                                         item_heights = new Hashtable ();
375                                 Refresh ();
376                         }
377                 }
378
379 #if NET_2_0
380                 [Browsable (true)]
381                 [DefaultValue (106)]
382                 [EditorBrowsable (EditorBrowsableState.Always)]
383                 [MWFCategory("Behavior")]
384                 public int DropDownHeight {
385                         get {
386                                 return drop_down_height;
387                         }
388                         set {
389                                 if (value < 1)
390                                         throw new ArgumentOutOfRangeException ("DropDownHeight", "DropDownHeight must be greater than 0.");
391                                         
392                                 drop_down_height = value;
393                                 IntegralHeight = false;
394                         }
395                 }
396 #endif
397
398                 [DefaultValue (ComboBoxStyle.DropDown)]
399                 [RefreshProperties(RefreshProperties.Repaint)]
400                 [MWFCategory("Appearance")]
401                 public ComboBoxStyle DropDownStyle {
402                         get { return dropdown_style; }
403                         set {
404                                 if (!Enum.IsDefined (typeof (ComboBoxStyle), value))
405                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for ComboBoxStyle", value));
406
407                                 if (dropdown_style == value)
408                                         return;
409
410                                 SuspendLayout ();
411
412                                 if (dropdown_style == ComboBoxStyle.Simple) {
413                                         if (listbox_ctrl != null) {
414                                                 Controls.RemoveImplicit (listbox_ctrl);
415                                                 listbox_ctrl.Dispose ();
416                                                 listbox_ctrl = null;
417                                         }
418                                 }
419
420                                 dropdown_style = value;
421                                 
422                                 if (dropdown_style == ComboBoxStyle.DropDownList && textbox_ctrl != null) {
423                                         Controls.RemoveImplicit (textbox_ctrl);
424                                         textbox_ctrl.Dispose ();
425                                         textbox_ctrl = null;
426                                 }
427
428                                 if (dropdown_style == ComboBoxStyle.Simple) {
429                                         show_dropdown_button = false;
430                                         
431                                         CreateComboListBox ();
432                                         Controls.AddImplicit (listbox_ctrl);
433                                         listbox_ctrl.Visible = true;
434
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;
440                                 } else {
441                                         show_dropdown_button = true;
442                                         button_state = ButtonState.Normal;
443                                 }
444         
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;
455
456                                         if (IsHandleCreated == true)
457                                                 Controls.AddImplicit (textbox_ctrl);
458 #if NET_2_0
459                                         SetTextBoxAutoCompleteData ();
460 #endif
461                                 }
462                                 
463                                 ResumeLayout ();
464                                 OnDropDownStyleChanged (EventArgs.Empty);
465                                 
466                                 LayoutComboBox ();
467                                 UpdateComboBoxBounds ();
468                                 Refresh ();
469                         }
470                 }
471
472                 [MWFCategory("Behavior")]
473                 public int DropDownWidth {
474                         get { 
475                                 if (dropdown_width == -1)
476                                         return Width;
477                                         
478                                 return dropdown_width; 
479                         }
480                         set {
481                                 if (dropdown_width == value)
482                                         return;
483                                         
484                                 if (value < 1)
485 #if NET_2_0
486                                         throw new ArgumentOutOfRangeException ("DropDownWidth",
487                                                 "The DropDownWidth value is less than one.");
488 #else
489                                         throw new ArgumentException ("The DropDownWidth value is less than one.");
490 #endif
491
492                                 dropdown_width = value;
493                         }
494                 }
495                 
496                 [Browsable (false)]
497                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
498                 public bool DroppedDown {
499                         get { 
500                                 if (dropdown_style == ComboBoxStyle.Simple)
501                                         return true;
502                                 
503                                 return dropped_down;
504                         }
505                         set {
506                                 if (dropdown_style == ComboBoxStyle.Simple || dropped_down == value)
507                                         return;
508                                         
509                                 if (value) 
510                                         DropDownListBox ();
511                                 else
512                                         listbox_ctrl.Hide ();
513                         }
514                 }
515
516 #if NET_2_0
517                 [DefaultValue (FlatStyle.Standard)]
518                 [Localizable (true)]
519                 [MWFCategory("Appearance")]
520                 public FlatStyle FlatStyle {
521                         get { return flat_style; }
522                         set {
523                                 if (!Enum.IsDefined (typeof (FlatStyle), value))
524                                         throw new InvalidEnumArgumentException ("FlatStyle", (int) value, typeof (FlatStyle));
525                                 
526                                 flat_style = value;
527                                 LayoutComboBox ();
528                                 Invalidate ();
529                         }
530                 }
531 #endif
532
533                 public override bool Focused {
534                         get { return base.Focused; }
535                 }
536
537                 public override Color ForeColor {
538                         get { return base.ForeColor; }
539                         set {
540                                 if (base.ForeColor == value)
541                                         return;
542                                 base.ForeColor = value;
543                                 Refresh ();
544                         }
545                 }
546
547                 [DefaultValue (true)]
548                 [Localizable (true)]
549                 [MWFCategory("Behavior")]
550                 public bool IntegralHeight {
551                         get { return integral_height; }
552                         set {
553                                 if (integral_height == value)
554                                         return;
555                                 integral_height = value;
556                                 UpdateComboBoxBounds ();
557                                 Refresh ();
558                         }
559                 }
560
561                 [Localizable (true)]
562                 [MWFCategory("Behavior")]
563                 public int ItemHeight {
564                         get {
565                                 if (item_height == -1) {
566                                         SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
567                                         item_height = (int) sz.Height;
568                                 }
569                                 return item_height;
570                         }
571                         set {
572                                 if (value < 1)
573 #if NET_2_0
574                                         throw new ArgumentOutOfRangeException ("ItemHeight",
575                                                 "The item height value is less than one.");
576 #else
577                                         throw new ArgumentException ("The item height value is less than one.");
578 #endif
579
580                                 item_height_specified = true;
581                                 item_height = value;
582                                 if (IntegralHeight)
583                                         UpdateComboBoxBounds ();
584                                 LayoutComboBox ();
585                                 Refresh ();
586                         }
587                 }
588
589                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
590                 [Localizable (true)]
591                 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
592 #if NET_2_0
593                 [MergableProperty (false)]
594 #endif
595                 [MWFCategory("Data")]
596                 public ComboBox.ObjectCollection Items {
597                         get { return items; }
598                 }
599
600                 [DefaultValue (8)]
601                 [Localizable (true)]
602                 [MWFCategory("Behavior")]
603                 public int MaxDropDownItems {
604                         get { return maxdrop_items; }
605                         set {
606                                 if (maxdrop_items == value)
607                                         return;
608                                 maxdrop_items = value;
609                         }
610                 }
611
612 #if NET_2_0
613                 public override Size MaximumSize {
614                         get { return base.MaximumSize; }
615                         set {
616                                 base.MaximumSize = new Size (value.Width, 0);
617                         }
618                 }
619 #endif
620
621                 [DefaultValue (0)]
622                 [Localizable (true)]
623                 [MWFCategory("Behavior")]
624                 public int MaxLength {
625                         get { return max_length; }
626                         set {
627                                 if (max_length == value)
628                                         return;
629
630                                 max_length = value;
631                                 
632                                 if (dropdown_style != ComboBoxStyle.DropDownList) {
633                                         if (value < 0) {
634                                                 value = 0;
635                                         }
636                                         textbox_ctrl.MaxLength = value;
637                                 }
638                         }
639                 }
640
641 #if NET_2_0
642                 public override Size MinimumSize {
643                         get { return base.MinimumSize; }
644                         set {
645                                 base.MinimumSize = new Size (value.Width, 0);
646                         }
647                 }
648                 
649                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
650                 [EditorBrowsable (EditorBrowsableState.Never)]
651                 [Browsable (false)]
652                 public new Padding Padding  {
653                         get { return base.Padding; }
654                         set { base.Padding = value; }
655                 }
656 #endif
657
658                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
659                 [Browsable (false)]
660                 public int PreferredHeight {
661                         get { return Font.Height + 8; }
662                 }
663
664                 [Browsable (false)]
665                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
666                 public override int SelectedIndex {
667                         get { return selected_index; }
668                         set {
669                                 if (selected_index == value)
670                                         return;
671
672                                 if (value <= -2 || value >= Items.Count)
673                                         throw new ArgumentOutOfRangeException ("SelectedIndex");
674                                 selected_index = value;
675
676                                 if (dropdown_style != ComboBoxStyle.DropDownList) {
677                                         if (value == -1)
678                                                 SetControlText (string.Empty, false);
679                                         else
680                                                 SetControlText (GetItemText (Items [value]), false);
681                                 }
682
683                                 if (DropDownStyle == ComboBoxStyle.DropDownList)
684                                         Invalidate ();
685
686                                 if (listbox_ctrl != null)
687                                         listbox_ctrl.HighlightedIndex = value;
688
689                                 OnSelectedValueChanged (new EventArgs ());
690                                 OnSelectedIndexChanged (new EventArgs ());
691                                 OnSelectedItemChanged (new EventArgs ());
692                         }
693                 }
694
695                 [Browsable (false)]
696                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
697                 [Bindable(true)]
698                 public object SelectedItem {
699                         get { return selected_index == -1 ? null : Items [selected_index]; }
700                         set {
701                                 object item = selected_index == -1 ? null : Items [selected_index];
702                                 if (item == value)
703                                         return;
704
705                                 if (value == null)
706                                         SelectedIndex = -1;
707                                 else
708                                         SelectedIndex = Items.IndexOf (value);
709                         }
710                 }
711                 
712                 [Browsable (false)]
713                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
714                 public string SelectedText {
715                         get {
716                                 if (dropdown_style == ComboBoxStyle.DropDownList)
717                                         return string.Empty;
718                                         
719                                 string retval = textbox_ctrl.SelectedText;
720                                 
721 #if ONLY_1_1
722                                 // On 1.1, the textbox will return null, combobox returns ""
723                                 if (retval == null && !textbox_ctrl.IsHandleCreated)
724                                         return string.Empty;
725 #endif                                  
726                                 return retval;
727                         }
728                         set {
729                                 if (dropdown_style == ComboBoxStyle.DropDownList)
730                                         return;
731                                 textbox_ctrl.SelectedText = value;
732                         }
733                 }
734
735                 [Browsable (false)]
736                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
737                 public int SelectionLength {
738                         get {
739                                 if (dropdown_style == ComboBoxStyle.DropDownList) 
740                                         return 0;
741                                 
742                                 int result = textbox_ctrl.SelectionLength;
743                                 return result == -1 ? 0 : result;
744                         }
745                         set {
746                                 if (dropdown_style == ComboBoxStyle.DropDownList) 
747                                         return;
748                                 if (textbox_ctrl.SelectionLength == value)
749                                         return;
750                                 textbox_ctrl.SelectionLength = value;
751                         }
752                 }
753
754                 [Browsable (false)]
755                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
756                 public int SelectionStart {
757                         get { 
758                                 if (dropdown_style == ComboBoxStyle.DropDownList) 
759                                         return 0;
760                                 return textbox_ctrl.SelectionStart;
761                         }
762                         set {
763                                 if (dropdown_style == ComboBoxStyle.DropDownList) 
764                                         return;
765                                 if (textbox_ctrl.SelectionStart == value)
766                                         return;
767                                 textbox_ctrl.SelectionStart = value;
768                         }
769                 }
770
771                 [DefaultValue (false)]
772                 [MWFCategory("Behavior")]
773                 public bool Sorted {
774                         get { return sorted; }
775                         set {
776                                 if (sorted == value)
777                                         return;
778                                 sorted = value;
779                                 SelectedIndex = -1;
780                                 if (sorted) {
781                                         Items.Sort ();
782                                         LayoutComboBox ();
783                                 }
784                         }
785                 }
786
787                 [Bindable (true)]
788                 [Localizable (true)]
789                 public override string Text {
790                         get {
791                                 if (dropdown_style != ComboBoxStyle.DropDownList) {
792                                         if (textbox_ctrl != null) {
793                                                 return textbox_ctrl.Text;
794                                         }
795                                 }
796                                 
797                                 if (SelectedItem != null)
798                                         return GetItemText (SelectedItem);
799                                 
800                                 return base.Text;
801                         }
802                         set {
803                                 if (value == null) {
804                                         if (SelectedIndex == -1) {
805                                                 if (dropdown_style != ComboBoxStyle.DropDownList)
806                                                         SetControlText (string.Empty, false);
807                                         } else {
808                                                 SelectedIndex = -1;
809                                         }
810                                         return;
811                                 }
812
813                                 // do nothing if value exactly matches text of selected item
814                                 if (SelectedItem != null && string.Compare (value, GetItemText (SelectedItem), false, CultureInfo.CurrentCulture) == 0)
815                                         return;
816
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);
820                                 if (index == -1) {
821                                         index = FindStringExact (value, -1, true);
822                                 }
823                                 if (index != -1) {
824                                         SelectedIndex = index;
825                                         return;
826                                 }
827
828                                 if (dropdown_style != ComboBoxStyle.DropDownList)
829                                         textbox_ctrl.Text = GetItemText (value);
830                         }
831                 }
832
833                 #endregion Public Properties
834
835                 #region Internal Properties
836                 internal Rectangle ButtonArea {
837                         get { return button_area; }
838                 }
839
840                 internal Rectangle TextArea {
841                         get { return text_area; }
842                 }
843                 #endregion
844
845                 #region UIA Framework Properties
846
847                 internal TextBox UIATextBox {
848                         get { return textbox_ctrl; }
849                 }
850
851                 #endregion UIA Framework Properties
852
853                 #region Public Methods
854 #if NET_2_0
855                 [Obsolete ("This method has been deprecated")]
856 #endif
857                 protected virtual void AddItemsCore (object[] value)
858                 {
859                         
860                 }
861
862                 public void BeginUpdate ()
863                 {
864                         suspend_ctrlupdate = true;
865                 }
866
867 #if NET_2_0
868                 protected override AccessibleObject CreateAccessibilityInstance ()
869                 {
870                         return base.CreateAccessibilityInstance ();
871                 }
872                 
873                 protected override void CreateHandle ()
874                 {
875                         base.CreateHandle ();
876                 }
877 #endif
878
879                 protected override void Dispose (bool disposing)
880                 {
881                         if (disposing) {
882                                 if (listbox_ctrl != null) {
883                                         listbox_ctrl.Dispose ();
884                                         Controls.RemoveImplicit (listbox_ctrl);
885                                         listbox_ctrl = null;
886                                 }
887                         
888                                 if (textbox_ctrl != null) {
889                                         Controls.RemoveImplicit (textbox_ctrl);
890                                         textbox_ctrl.Dispose ();
891                                         textbox_ctrl = null;
892                                 }
893                         }
894                         
895                         base.Dispose (disposing);
896                 }
897
898                 public void EndUpdate ()
899                 {
900                         suspend_ctrlupdate = false;
901                         UpdatedItems ();
902                         Refresh ();
903                 }
904
905                 public int FindString (string s)
906                 {
907                         return FindString (s, -1);
908                 }
909
910                 public int FindString (string s, int startIndex)
911                 {
912                         if (s == null || Items.Count == 0) 
913                                 return -1;
914
915 #if NET_2_0
916                         if (startIndex < -1 || startIndex >= Items.Count)
917 #else
918                         if (startIndex < -1 || startIndex >= Items.Count - 1)
919 #endif
920                                 throw new ArgumentOutOfRangeException ("startIndex");
921
922                         int i = startIndex;
923 #if NET_2_0
924                         if (i == (Items.Count - 1))
925                                 i = -1;
926 #endif
927                         do {
928                                 i++;
929                                 if (string.Compare (s, 0, GetItemText (Items [i]), 0, s.Length, true) == 0)
930                                         return i;
931                                 if (i == (Items.Count - 1))
932                                         i = -1;
933                         } while (i != startIndex);
934
935                         return -1;
936                 }
937
938                 public int FindStringExact (string s)
939                 {
940                         return FindStringExact (s, -1);
941                 }
942
943                 public int FindStringExact (string s, int startIndex)
944                 {
945                         return FindStringExact (s, startIndex, true);
946                 }
947
948                 private int FindStringExact (string s, int startIndex, bool ignoreCase)
949                 {
950                         if (s == null || Items.Count == 0) 
951                                 return -1;
952
953 #if NET_2_0
954                         if (startIndex < -1 || startIndex >= Items.Count)
955 #else
956                         if (startIndex < -1 || startIndex >= Items.Count - 1)
957 #endif
958                                 throw new ArgumentOutOfRangeException ("startIndex");
959
960                         int i = startIndex;
961 #if NET_2_0
962                         if (i == (Items.Count - 1))
963                                 i = -1;
964 #endif
965                         do {
966                                 i++;
967                                 if (string.Compare (s, GetItemText (Items [i]), ignoreCase, CultureInfo.CurrentCulture) == 0)
968                                         return i;
969                                 if (i == (Items.Count - 1))
970                                         i = -1;
971                         } while (i != startIndex);
972
973                         return -1;
974                 }
975
976                 public int GetItemHeight (int index)
977                 {
978                         if (DrawMode == DrawMode.OwnerDrawVariable && IsHandleCreated) {
979
980                                 if (index < 0 || index >= Items.Count )
981                                         throw new ArgumentOutOfRangeException ("The item height value is less than zero");
982                                 
983                                 object item = Items [index];
984                                 if (item_heights.Contains (item))
985                                         return (int) item_heights [item];
986                                 
987                                 MeasureItemEventArgs args = new MeasureItemEventArgs (DeviceContext, index, ItemHeight);
988                                 OnMeasureItem (args);
989                                 item_heights [item] = args.ItemHeight;
990                                 return args.ItemHeight;
991                         }
992
993                         return ItemHeight;
994                 }
995
996                 protected override bool IsInputKey (Keys keyData)
997                 {
998                         switch (keyData & ~Keys.Modifiers) {
999                         case Keys.Up:
1000                         case Keys.Down:
1001                         case Keys.Left:
1002                         case Keys.Right:
1003                         case Keys.PageUp:
1004                         case Keys.PageDown:
1005                         case Keys.Home:
1006                         case Keys.End:
1007                                 return true;
1008                         
1009                         default:
1010                                 return false;
1011                         }
1012                 }
1013
1014                 protected override void OnBackColorChanged (EventArgs e)
1015                 {
1016                         base.OnBackColorChanged (e);
1017
1018                         if (textbox_ctrl != null)
1019                                 textbox_ctrl.BackColor = BackColor;
1020                 }
1021
1022                 protected override void OnDataSourceChanged (EventArgs e)
1023                 {
1024                         base.OnDataSourceChanged (e);
1025                         BindDataItems ();
1026                         
1027                         if (DataSource == null || DataManager == null) {
1028                                 SelectedIndex = -1;
1029                         } 
1030                         else {
1031                                 SelectedIndex = DataManager.Position;
1032                         }
1033                 }
1034
1035                 protected override void OnDisplayMemberChanged (EventArgs e)
1036                 {
1037                         base.OnDisplayMemberChanged (e);
1038
1039                         if (DataManager == null)
1040                                 return;
1041
1042                         if (selected_index != -1 && DropDownStyle != ComboBoxStyle.DropDownList)
1043                                 SetControlText (GetItemText (Items [selected_index]), true);
1044
1045                         if (!IsHandleCreated)
1046                                 return;
1047
1048                         SelectedIndex = DataManager.Position;
1049                         Invalidate ();
1050                 }
1051
1052                 protected virtual void OnDrawItem (DrawItemEventArgs e)
1053                 {
1054                         switch (DrawMode) {
1055                         case DrawMode.OwnerDrawFixed:
1056                         case DrawMode.OwnerDrawVariable:
1057                                 DrawItemEventHandler eh = (DrawItemEventHandler)(Events [DrawItemEvent]);
1058                                 if (eh != null)
1059                                         eh (this, e);
1060                                 break;
1061                         default:
1062                                 ThemeEngine.Current.DrawComboBoxItem (this, e);
1063                                 break;
1064                         }
1065                 }
1066
1067                 protected virtual void OnDropDown (EventArgs e)
1068                 {
1069                         EventHandler eh = (EventHandler)(Events [DropDownEvent]);
1070                         if (eh != null)
1071                                 eh (this, e);
1072                 }
1073
1074 #if NET_2_0
1075                 protected virtual void OnDropDownClosed (EventArgs e)
1076                 {
1077                         EventHandler eh = (EventHandler) Events [DropDownClosedEvent];
1078                         if (eh != null)
1079                                 eh (this, e);
1080                 }
1081 #endif
1082
1083                 protected virtual void OnDropDownStyleChanged (EventArgs e)
1084                 {
1085                         EventHandler eh = (EventHandler)(Events [DropDownStyleChangedEvent]);
1086                         if (eh != null)
1087                                 eh (this, e);
1088                 }
1089
1090                 protected override void OnFontChanged (EventArgs e)
1091                 {
1092                         base.OnFontChanged (e);
1093
1094                         if (textbox_ctrl != null)
1095                                 textbox_ctrl.Font = Font;
1096                         
1097                         if (!item_height_specified) {
1098                                 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
1099                                 item_height = (int) sz.Height;
1100                         }
1101
1102                         if (IntegralHeight)
1103                                 UpdateComboBoxBounds ();
1104
1105                         LayoutComboBox ();
1106                 }
1107
1108                 protected override void OnForeColorChanged (EventArgs e)
1109                 {
1110                         base.OnForeColorChanged (e);
1111                         if (textbox_ctrl != null)
1112                                 textbox_ctrl.ForeColor = ForeColor;
1113                 }
1114
1115                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1116                 protected override void OnGotFocus (EventArgs e)
1117                 {
1118                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1119                                 // We draw DDL styles manually, so they require a
1120                                 // refresh to have their selection drawn
1121                                 Invalidate ();
1122                         }
1123                         
1124                         if (textbox_ctrl != null) {
1125                                 textbox_ctrl.SetSelectable (false);
1126                                 textbox_ctrl.ShowSelection = true;
1127                                 textbox_ctrl.ActivateCaret (true);
1128                                 textbox_ctrl.SelectAll ();
1129                         }
1130
1131                         base.OnGotFocus (e);
1132                 }
1133
1134                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1135                 protected override void OnLostFocus (EventArgs e)
1136                 {
1137                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1138                                 // We draw DDL styles manually, so they require a
1139                                 // refresh to have their selection drawn
1140                                 Invalidate ();
1141                         }
1142
1143                         if (listbox_ctrl != null && dropped_down) {
1144                                 listbox_ctrl.HideWindow ();
1145                         }
1146
1147                         if (textbox_ctrl != null) {
1148                                 textbox_ctrl.SetSelectable (true);
1149                                 textbox_ctrl.ActivateCaret (false);
1150                                 textbox_ctrl.ShowSelection = false;
1151                                 textbox_ctrl.SelectionLength = 0;
1152                         }
1153
1154                         base.OnLostFocus (e);
1155                 }
1156
1157                 protected override void OnHandleCreated (EventArgs e)
1158                 {
1159                         base.OnHandleCreated (e);
1160
1161                         SetBoundsInternal (Left, Top, Width, PreferredHeight, BoundsSpecified.None);
1162
1163                         if (textbox_ctrl != null)
1164                                 Controls.AddImplicit (textbox_ctrl);
1165
1166                         LayoutComboBox ();
1167                         UpdateComboBoxBounds ();
1168                 }
1169
1170                 protected override void OnHandleDestroyed (EventArgs e)
1171                 {
1172                         base.OnHandleDestroyed (e);
1173                 }
1174
1175                 protected override void OnKeyPress (KeyPressEventArgs e)
1176                 {
1177                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1178                                 int index = FindStringCaseInsensitive (e.KeyChar.ToString (), SelectedIndex + 1);
1179                                 if (index != -1) {
1180                                         SelectedIndex = index;
1181                                         if (DroppedDown) { //Scroll into view
1182                                                 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1183                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1184                                                 // Or, selecting an item earlier in the list.
1185                                                 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1186                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1187                                         }
1188                                 }
1189                         }
1190
1191                         base.OnKeyPress (e);
1192                 }
1193
1194                 protected virtual void OnMeasureItem (MeasureItemEventArgs e)
1195                 {
1196                         MeasureItemEventHandler eh = (MeasureItemEventHandler)(Events [MeasureItemEvent]);
1197                         if (eh != null)
1198                                 eh (this, e);
1199                 }
1200
1201                 protected override void OnParentBackColorChanged (EventArgs e)
1202                 {
1203                         base.OnParentBackColorChanged (e);
1204                 }
1205
1206                 protected override void OnResize (EventArgs e)
1207                 {
1208                         LayoutComboBox ();
1209                         if (listbox_ctrl != null)
1210                                 listbox_ctrl.CalcListBoxArea ();
1211                 }
1212
1213                 protected override void OnSelectedIndexChanged (EventArgs e)
1214                 {
1215                         base.OnSelectedIndexChanged (e);
1216
1217                         EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
1218                         if (eh != null)
1219                                 eh (this, e);
1220                 }
1221
1222                 protected virtual void OnSelectedItemChanged (EventArgs e)
1223                 {
1224                 }
1225
1226                 protected override void OnSelectedValueChanged (EventArgs e)
1227                 {
1228                         base.OnSelectedValueChanged (e);
1229                 }
1230
1231                 protected virtual void OnSelectionChangeCommitted (EventArgs e)
1232                 {
1233                         EventHandler eh = (EventHandler)(Events [SelectionChangeCommittedEvent]);
1234                         if (eh != null)
1235                                 eh (this, e);
1236                 }
1237
1238                 protected override void RefreshItem (int index)
1239                 {
1240                         if (index < 0 || index >= Items.Count)
1241                                 throw new ArgumentOutOfRangeException ("index");
1242                                 
1243                         if (draw_mode == DrawMode.OwnerDrawVariable)
1244                                 item_heights.Remove (Items [index]);
1245                 }
1246
1247 #if NET_2_0
1248                 protected override void RefreshItems ()
1249                 {
1250                         for (int i = 0; i < Items.Count; i++) {
1251                                 RefreshItem (i);
1252                         }
1253                 }
1254
1255                 public override void ResetText ()
1256                 {
1257                         Text = String.Empty;
1258                 }
1259                 
1260                 protected override bool ProcessKeyEventArgs (ref Message m)
1261                 {
1262                         return base.ProcessKeyEventArgs (ref m);
1263                 }
1264
1265                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1266                 protected override void OnKeyDown (KeyEventArgs e)
1267                 {
1268                         base.OnKeyDown (e);
1269                 }
1270
1271                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1272                 protected override void OnValidating (CancelEventArgs e)
1273                 {
1274                         base.OnValidating (e);
1275                 }
1276
1277                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1278                 protected override void OnTextChanged (EventArgs e)
1279                 {
1280                         base.OnTextChanged (e);
1281                 }
1282
1283 #if NET_2_0
1284                 protected virtual void OnTextUpdate (EventArgs e)
1285                 {
1286                         EventHandler eh = (EventHandler) Events [TextUpdateEvent];
1287                         if (eh != null)
1288                                 eh (this, e);
1289                 }
1290 #endif
1291                 protected override void OnMouseLeave (EventArgs e)
1292                 {
1293 #if NET_2_0
1294                         if (flat_style == FlatStyle.Popup)
1295                                 Invalidate ();
1296 #endif
1297                         base.OnMouseLeave (e);
1298                 }
1299                 
1300                 protected override void OnMouseEnter (EventArgs e)
1301                 {
1302 #if NET_2_0
1303                         if (flat_style == FlatStyle.Popup)
1304                                 Invalidate ();
1305 #endif
1306                         base.OnMouseEnter (e);
1307                 }
1308 #endif
1309
1310 #if NET_2_0
1311                 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
1312                 {
1313                         base.ScaleControl (factor, specified);
1314                 }
1315 #endif
1316
1317                 public void Select (int start, int length)
1318                 {
1319                         if (start < 0)
1320                                 throw new ArgumentException ("Start cannot be less than zero");
1321                                 
1322                         if (length < 0)
1323                                 throw new ArgumentException ("length cannot be less than zero");
1324                                 
1325                         if (dropdown_style == ComboBoxStyle.DropDownList)
1326                                 return;
1327
1328                         textbox_ctrl.Select (start, length);
1329                 }
1330
1331                 public void SelectAll ()
1332                 {
1333                         if (dropdown_style == ComboBoxStyle.DropDownList)
1334                                 return;
1335
1336                         if (textbox_ctrl != null) {
1337                                 textbox_ctrl.ShowSelection = true;
1338                                 textbox_ctrl.SelectAll ();
1339                         }
1340                 }
1341
1342                 protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified)
1343                 {
1344                         bool vertically_anchored = (Anchor & AnchorStyles.Top) != 0 && (Anchor & AnchorStyles.Bottom) != 0;
1345                         bool vertically_docked = Dock == DockStyle.Left || Dock == DockStyle.Right || Dock == DockStyle.Fill;
1346
1347                         if ((specified & BoundsSpecified.Height) != 0 ||
1348                                 (specified == BoundsSpecified.None && (vertically_anchored || vertically_docked))) {
1349
1350                                 requested_height = height;
1351                                 height = SnapHeight (height);
1352                         }
1353
1354                         base.SetBoundsCore (x, y, width, height, specified);
1355                 }
1356
1357                 protected override void SetItemCore (int index, object value)
1358                 {
1359                         if (index < 0 || index >= Items.Count)
1360                                 return;
1361
1362                         Items[index] = value;
1363                 }
1364
1365                 protected override void SetItemsCore (IList value)
1366                 {
1367                         BeginUpdate ();
1368                         try {
1369                                 Items.Clear ();
1370                                 Items.AddRange (value);
1371                         } finally {
1372                                 EndUpdate ();
1373                         }
1374                 }
1375
1376                 public override string ToString ()
1377                 {
1378                         return base.ToString () + ", Items.Count:" + Items.Count;
1379                 }
1380
1381                 protected override void WndProc (ref Message m)
1382                 {
1383                         switch ((Msg) m.Msg) {
1384                         case Msg.WM_KEYUP:
1385                         case Msg.WM_KEYDOWN:
1386                                 Keys keys = (Keys) m.WParam.ToInt32 ();
1387                                 if (keys == Keys.Up || keys == Keys.Down)
1388                                         break;
1389                                 goto case Msg.WM_CHAR;
1390                         case Msg.WM_CHAR:
1391                                 if (textbox_ctrl != null)
1392                                         XplatUI.SendMessage (textbox_ctrl.Handle, (Msg) m.Msg, m.WParam, m.LParam);
1393                                 break;
1394                         case Msg.WM_MOUSELEAVE:
1395                                 Point location = PointToClient (Control.MousePosition);
1396                                 if (ClientRectangle.Contains (location))
1397                                         return;
1398                                 break;
1399                         default:
1400                                 break;
1401                         }
1402                         base.WndProc (ref m);
1403                 }
1404
1405                 #endregion Public Methods
1406
1407                 #region Private Methods
1408 #if NET_2_0
1409                 void OnAutoCompleteCustomSourceChanged(object sender, CollectionChangeEventArgs e) {
1410                         if(auto_complete_source == AutoCompleteSource.CustomSource) {
1411                                 //FIXME: handle add, remove and refresh events in AutoComplete algorithm.
1412                         }
1413                 }
1414 #endif
1415
1416                 internal override bool InternalCapture {
1417                         get { return Capture; }
1418                         set {}
1419                 }
1420                 
1421                 void LayoutComboBox ()
1422                 {
1423                         int border = ThemeEngine.Current.Border3DSize.Width;
1424
1425                         text_area = ClientRectangle;
1426                         text_area.Height = PreferredHeight;
1427                         
1428                         listbox_area = ClientRectangle;
1429                         listbox_area.Y = text_area.Bottom + 3;
1430                         listbox_area.Height -= (text_area.Height + 2);
1431
1432                         Rectangle prev_button_area = button_area;
1433
1434                         if (DropDownStyle == ComboBoxStyle.Simple)
1435                                 button_area = Rectangle.Empty;
1436                         else {
1437                                 button_area = text_area;
1438                                 button_area.X = text_area.Right - button_width - border;
1439                                 button_area.Y = text_area.Y + border;
1440                                 button_area.Width = button_width;
1441                                 button_area.Height = text_area.Height - 2 * border;
1442 #if NET_2_0
1443                                 if (flat_style == FlatStyle.Popup || flat_style == FlatStyle.Flat) {
1444                                         button_area.Inflate (1, 1);
1445                                         button_area.X += 2;
1446                                         button_area.Width -= 2;
1447                                 }
1448 #endif
1449                         }
1450
1451                         if (button_area != prev_button_area) {
1452                                 prev_button_area.Y -= border;
1453                                 prev_button_area.Width += border;
1454                                 prev_button_area.Height += 2 * border;
1455                                 Invalidate (prev_button_area);
1456                                 Invalidate (button_area);
1457                         }
1458
1459                         if (textbox_ctrl != null) {
1460                                 int text_border = border + 1;
1461                                 textbox_ctrl.Location = new Point (text_area.X + text_border, text_area.Y + text_border);
1462                                 textbox_ctrl.Width = text_area.Width - button_area.Width - text_border * 2;
1463                                 textbox_ctrl.Height = text_area.Height - text_border * 2;
1464                         }
1465
1466                         if (listbox_ctrl != null && dropdown_style == ComboBoxStyle.Simple) {
1467                                 listbox_ctrl.Location = listbox_area.Location;
1468                                 listbox_ctrl.CalcListBoxArea ();
1469                         }
1470                 }
1471
1472                 private void CreateComboListBox ()
1473                 {
1474                         listbox_ctrl = new ComboListBox (this);
1475                         listbox_ctrl.HighlightedIndex = SelectedIndex;
1476                 }
1477                 
1478                 internal void Draw (Rectangle clip, Graphics dc)
1479                 {
1480                         Theme theme = ThemeEngine.Current;
1481                         FlatStyle style = FlatStyle.Standard;
1482                         bool is_flat = false;
1483
1484 #if NET_2_0
1485                         style = this.FlatStyle;
1486                         is_flat = style == FlatStyle.Flat || style == FlatStyle.Popup;
1487 #endif
1488
1489                         theme.ComboBoxDrawBackground (this, dc, clip, style);
1490
1491                         int border = theme.Border3DSize.Width;
1492
1493                         // No edit control, we paint the edit ourselves
1494                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1495                                 DrawItemState state = DrawItemState.None;
1496                                 Rectangle item_rect = text_area;
1497                                 item_rect.X += border;
1498                                 item_rect.Y += border;
1499                                 item_rect.Width -= (button_area.Width + 2 * border);
1500                                 item_rect.Height -= 2 * border;
1501                                 
1502                                 if (Focused) {
1503                                         state = DrawItemState.Selected;
1504                                         state |= DrawItemState.Focus;
1505                                 }
1506                                 
1507                                 state |= DrawItemState.ComboBoxEdit;
1508                                 OnDrawItem (new DrawItemEventArgs (dc, Font, item_rect, SelectedIndex, state, ForeColor, BackColor));
1509                         }
1510                         
1511                         if (show_dropdown_button) {
1512                                 ButtonState current_state;
1513                                 if (is_enabled)
1514                                         current_state = button_state;
1515                                 else
1516                                         current_state = ButtonState.Inactive;
1517
1518                                 if (is_flat || theme.ComboBoxNormalDropDownButtonHasTransparentBackground (this, current_state))
1519                                         dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), button_area);
1520
1521                                 if (is_flat) {
1522                                         theme.DrawFlatStyleComboButton (dc, button_area, current_state);
1523                                 } else {
1524                                         theme.ComboBoxDrawNormalDropDownButton (this, dc, clip, button_area, current_state); 
1525                                 }
1526                         }
1527                 }
1528
1529                 internal bool DropDownButtonEntered {
1530                         get { return drop_down_button_entered; }
1531                         private set {
1532                                 if (drop_down_button_entered == value)
1533                                         return;
1534                                 drop_down_button_entered = value;
1535                                 if (ThemeEngine.Current.ComboBoxDropDownButtonHasHotElementStyle (this))
1536                                         Invalidate (button_area);
1537                         }
1538                 }
1539
1540                 internal void DropDownListBox ()
1541                 {
1542                         DropDownButtonEntered = false;
1543
1544                         if (DropDownStyle == ComboBoxStyle.Simple)
1545                                 return;
1546                         
1547                         if (listbox_ctrl == null)
1548                                 CreateComboListBox ();
1549
1550                         listbox_ctrl.Location = PointToScreen (new Point (text_area.X, text_area.Y + text_area.Height));
1551
1552                         FindMatchOrSetIndex(SelectedIndex);
1553
1554                         if (listbox_ctrl.ShowWindow ())
1555                                 dropped_down = true;
1556
1557                         button_state = ButtonState.Pushed;
1558                         if (dropdown_style == ComboBoxStyle.DropDownList)
1559                                 Invalidate (text_area);
1560                 }
1561                 
1562                 internal void DropDownListBoxFinished ()
1563                 {
1564                         if (DropDownStyle == ComboBoxStyle.Simple)
1565                                 return;
1566                                 
1567                         FindMatchOrSetIndex (SelectedIndex);
1568                         button_state = ButtonState.Normal;
1569                         Invalidate (button_area);
1570                         dropped_down = false;
1571 #if NET_2_0
1572                         OnDropDownClosed (EventArgs.Empty);
1573 #endif
1574                         /*
1575                          * Apples X11 looses override-redirect when doing a Unmap/Map on a previously mapped window
1576                          * this causes the popup to appear under the main form.  This is horrible but necessary
1577                          */
1578                          
1579                          // If the user opens a new form in an event, it will close our dropdown,
1580                          // so we need a null check here
1581                          if (listbox_ctrl != null) {
1582                                 listbox_ctrl.Dispose ();
1583                                 listbox_ctrl = null;
1584                         }
1585                 }
1586                 
1587                 private int FindStringCaseInsensitive (string search)
1588                 {
1589                         if (search.Length == 0) {
1590                                 return -1;
1591                         }
1592                         
1593                         for (int i = 0; i < Items.Count; i++) 
1594                         {
1595                                 if (String.Compare (GetItemText (Items[i]), 0, search, 0, search.Length, true) == 0)
1596                                         return i;
1597                         }
1598
1599                         return -1;
1600                 }
1601
1602                 // Search in the list for the substring, starting the search at the list 
1603                 // position specified, the search wraps thus covering all the list.
1604                 internal int FindStringCaseInsensitive (string search, int start_index)
1605                 {
1606                         if (search.Length == 0) {
1607                                 return -1;
1608                         }
1609                         // Accept from first item to after last item. i.e. all cases of (SelectedIndex+1).
1610                         if (start_index < 0 || start_index > Items.Count)
1611                                 throw new ArgumentOutOfRangeException("start_index");
1612
1613                         for (int i = 0; i < Items.Count; i++) {
1614                                 int index = (i + start_index) % Items.Count;
1615                                 if (String.Compare (GetItemText (Items [index]), 0, search, 0, search.Length, true) == 0)
1616                                         return index;
1617                         }
1618
1619                         return -1;
1620                 }
1621
1622                 internal override bool IsInputCharInternal (char charCode)
1623                 {
1624                         return true;
1625                 }
1626
1627                 internal override ContextMenu ContextMenuInternal {
1628                         get {
1629                                 return base.ContextMenuInternal;
1630                         }
1631                         set {
1632                                 base.ContextMenuInternal = value;
1633                                 if (textbox_ctrl != null) {
1634                                         textbox_ctrl.ContextMenu = value;
1635                                 }
1636                         }
1637                 }
1638
1639                 internal void RestoreContextMenu ()
1640                 {
1641                         textbox_ctrl.RestoreContextMenu ();
1642                 }
1643
1644                 private void OnKeyDownCB(object sender, KeyEventArgs e)
1645                 {
1646                         if (Items.Count == 0)
1647                                 return;
1648
1649                         int offset;
1650                         switch (e.KeyCode) 
1651                         {
1652                                 case Keys.Up:
1653                                         FindMatchOrSetIndex(Math.Max(SelectedIndex - 1, 0));
1654
1655                                         if (DroppedDown)
1656                                                 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1657                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1658                                         break;
1659         
1660                                 case Keys.Down:
1661                                         if ((e.Modifiers & Keys.Alt) == Keys.Alt)
1662                                                 DropDownListBox ();
1663                                         else
1664                                                 FindMatchOrSetIndex(Math.Min(SelectedIndex + 1, Items.Count - 1));
1665                                                 
1666                                         if (DroppedDown)
1667                                                 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1668                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1669                                         break;
1670                                 
1671                                 case Keys.PageUp:
1672                                         offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1673                                         if (offset < 1)
1674                                                 offset = 1;
1675
1676                                         SelectedIndex = Math.Max (SelectedIndex - offset, 0);
1677
1678                                         if (DroppedDown)
1679                                                 if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1680                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1681                                         break;
1682         
1683                                 case Keys.PageDown:
1684                                         if (SelectedIndex == -1) {
1685                                                 SelectedIndex = 0;
1686                                                 if (dropdown_style != ComboBoxStyle.Simple)
1687                                                         return;
1688                                         }
1689
1690                                         offset = listbox_ctrl == null ? MaxDropDownItems - 1 : listbox_ctrl.page_size - 1;
1691                                         if (offset < 1)
1692                                                 offset = 1;
1693
1694                                         SelectedIndex = Math.Min (SelectedIndex + offset, Items.Count - 1);
1695
1696                                         if (DroppedDown)
1697                                                 if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1698                                                         listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1699                                         break;
1700                                 
1701                                 case Keys.Enter:        
1702                                 case Keys.Escape:
1703                                         DropDownListBoxFinished ();
1704                                         break;
1705                                         
1706                                 case Keys.Home:
1707                                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1708                                                 SelectedIndex = 0;
1709
1710                                                 if (DroppedDown)
1711                                                         if (SelectedIndex < listbox_ctrl.FirstVisibleItem ())
1712                                                                 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.FirstVisibleItem ());
1713                                         }
1714                                         
1715                                         break;
1716                                 case Keys.End:
1717                                         if (dropdown_style == ComboBoxStyle.DropDownList) {
1718                                                 SelectedIndex = Items.Count - 1;
1719
1720                                                 if (DroppedDown)
1721                                                         if (SelectedIndex >= listbox_ctrl.LastVisibleItem ())
1722                                                                 listbox_ctrl.Scroll (SelectedIndex - listbox_ctrl.LastVisibleItem () + 1);
1723                                         }
1724                                         
1725                                         break;
1726                                 default:
1727                                         break;
1728                         }
1729                 }
1730
1731                 // If no item is currently selected, and an item is found matching the text 
1732                 // in the textbox, then selected that item.  Otherwise the item at the given 
1733                 // index is selected.
1734                 private void FindMatchOrSetIndex(int index)
1735                 {
1736                         int match = -1;
1737                         if (SelectedIndex == -1 && Text.Length != 0)
1738                                 match = FindStringCaseInsensitive(Text);
1739                         if (match != -1)
1740                                 SelectedIndex = match;
1741                         else
1742                                 SelectedIndex = index;
1743                 }
1744                 
1745                 void OnMouseDownCB (object sender, MouseEventArgs e)
1746                 {
1747                         Rectangle area;
1748                         if (DropDownStyle == ComboBoxStyle.DropDownList)
1749                                 area = ClientRectangle;
1750                         else
1751                                 area = button_area;
1752
1753                         if (area.Contains (e.X, e.Y)) {
1754                                 if (Items.Count > 0)
1755                                         DropDownListBox ();
1756                                 else {
1757                                         button_state = ButtonState.Pushed;
1758                                         OnDropDown (EventArgs.Empty);
1759                                 }
1760                                 
1761                                 Invalidate (button_area);
1762                                 Update ();
1763                         }
1764                         Capture = true;
1765                 }
1766
1767                 void OnMouseEnter (object sender, EventArgs e)
1768                 {
1769                         if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this))
1770                                 Invalidate ();
1771                 }
1772
1773                 void OnMouseLeave (object sender, EventArgs e)
1774                 {
1775                         if (ThemeEngine.Current.CombBoxBackgroundHasHotElementStyle (this)) {
1776                                 drop_down_button_entered = false;
1777                                 Invalidate ();
1778                         } else {
1779                                 if (show_dropdown_button)
1780                                         DropDownButtonEntered = false;
1781                         }
1782                 }
1783
1784                 void OnMouseMoveCB (object sender, MouseEventArgs e)
1785                 {
1786                         if (show_dropdown_button && !dropped_down)
1787                                 DropDownButtonEntered = button_area.Contains (e.Location);
1788
1789                         if (DropDownStyle == ComboBoxStyle.Simple)
1790                                 return;
1791
1792                         if (listbox_ctrl != null && listbox_ctrl.Visible) {
1793                                 Point location = listbox_ctrl.PointToClient (Control.MousePosition);
1794                                 if (listbox_ctrl.ClientRectangle.Contains (location))
1795                                         listbox_ctrl.Capture = true;
1796                         }
1797                 }
1798
1799                 void OnMouseUpCB (object sender, MouseEventArgs e)
1800                 {
1801                         Capture = false;
1802                         
1803                         button_state = ButtonState.Normal;
1804                         Invalidate (button_area);
1805
1806                         OnClick (EventArgs.Empty);
1807
1808                         if (dropped_down)
1809                                 listbox_ctrl.Capture = true;
1810                 }
1811
1812                 private void OnMouseWheelCB (object sender, MouseEventArgs me)
1813                 {
1814                         if (Items.Count == 0)
1815                                 return;
1816
1817                         if (listbox_ctrl != null && listbox_ctrl.Visible) {
1818                                 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
1819                                 listbox_ctrl.Scroll (-lines);
1820                         } else {
1821                                 int lines = me.Delta / 120;
1822                                 int index = SelectedIndex - lines;
1823                                 if (index < 0)
1824                                         index = 0;
1825                                 else if (index >= Items.Count)
1826                                         index = Items.Count - 1;
1827                                 SelectedIndex = index;
1828                         }
1829                 }
1830
1831                 internal override void OnPaintInternal (PaintEventArgs pevent)
1832                 {
1833                         if (suspend_ctrlupdate)
1834                                 return;
1835
1836                         Draw (ClientRectangle, pevent.Graphics);
1837                 }
1838                 
1839                 private void OnTextBoxClick (object sender, EventArgs e)
1840                 {
1841                         OnClick (e);
1842                 }
1843
1844                 private void OnTextChangedEdit (object sender, EventArgs e)
1845                 {
1846                         if (process_textchanged_event == false)
1847                                 return; 
1848
1849                         int item = FindStringCaseInsensitive (textbox_ctrl.Text);
1850                         
1851                         if (item == -1) {
1852                                 // Setting base.Text below will raise this event
1853                                 // if we found something
1854                                 OnTextChanged (EventArgs.Empty);
1855                                 return;
1856                         }
1857                         
1858                         // TODO:  THIS IS BROKEN-ISH
1859                         // I don't think we should hilight, and setting the top item does weirdness
1860                         // when there is no scrollbar
1861                         
1862                         if (listbox_ctrl != null) {
1863                                 listbox_ctrl.SetTopItem (item);
1864                                 listbox_ctrl.HighlightedIndex = item;
1865                         }
1866
1867                         base.Text = textbox_ctrl.Text;
1868                 }
1869
1870                 private void OnTextKeyPress (object sender, KeyPressEventArgs e)
1871                 {
1872                         selected_index = -1;
1873                 }
1874
1875                 internal void SetControlText (string s, bool suppressTextChanged)
1876                 {
1877                         if (suppressTextChanged)
1878                                 process_textchanged_event = false;
1879                                 
1880                         textbox_ctrl.Text = s;
1881                         textbox_ctrl.SelectAll ();
1882                         process_textchanged_event = true;
1883                 }
1884                 
1885                 void UpdateComboBoxBounds ()
1886                 {
1887                         if (requested_height == -1)
1888                                 return;
1889
1890                         // Save the requested height since set bounds can destroy it
1891                         int save_height = requested_height;
1892                         SetBounds (bounds.X, bounds.Y, bounds.Width, SnapHeight (requested_height),
1893                                 BoundsSpecified.Height);
1894                         requested_height = save_height;
1895                 }
1896
1897                 int SnapHeight (int height)
1898                 {
1899                         if (DropDownStyle == ComboBoxStyle.Simple && height > PreferredHeight) {
1900                                 if (IntegralHeight) {
1901                                         int border = ThemeEngine.Current.Border3DSize.Height;
1902                                         int lb_height = (height - PreferredHeight - 2) - border * 2;
1903                                         if (lb_height > ItemHeight) {
1904                                                 int partial = (lb_height) % ItemHeight;
1905                                                 height -= partial;
1906                                         } else if (lb_height < ItemHeight)
1907                                                 height = PreferredHeight;
1908                                 }
1909                         } else
1910                                 height = PreferredHeight;
1911
1912                         return height;
1913                 }
1914
1915                 private void UpdatedItems ()
1916                 {
1917                         if (listbox_ctrl != null) {
1918                                 listbox_ctrl.UpdateLastVisibleItem ();
1919                                 listbox_ctrl.CalcListBoxArea ();
1920                                 listbox_ctrl.Refresh ();
1921                         }
1922                 }
1923
1924                 #endregion Private Methods
1925
1926                 [ListBindableAttribute (false)]
1927                 public class ObjectCollection : IList, ICollection, IEnumerable
1928                 {
1929
1930                         private ComboBox owner;
1931                         internal ArrayList object_items = new ArrayList ();
1932                         
1933                         #region UIA Framework Events
1934
1935 #if NET_2_0
1936                         //NOTE:
1937                         //      We are using Reflection to add/remove internal events.
1938                         //      Class ListProvider uses the events.
1939                         //
1940                         //Event used to generate UIA StructureChangedEvent
1941                         static object UIACollectionChangedEvent = new object ();
1942
1943                         internal event CollectionChangeEventHandler UIACollectionChanged {
1944                                 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
1945                                 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
1946                         }
1947                         
1948                         internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
1949                         {
1950                                 CollectionChangeEventHandler eh
1951                                         = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
1952                                 if (eh != null)
1953                                         eh (owner, args);
1954                         }
1955 #endif
1956
1957                         #endregion UIA Framework Events
1958
1959                         public ObjectCollection (ComboBox owner)
1960                         {
1961                                 this.owner = owner;
1962                         }
1963
1964                         #region Public Properties
1965                         public int Count {
1966                                 get { return object_items.Count; }
1967                         }
1968
1969                         public bool IsReadOnly {
1970                                 get { return false; }
1971                         }
1972
1973                         [Browsable (false)]
1974                         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1975                         public virtual object this [int index] {
1976                                 get {
1977                                         if (index < 0 || index >= Count)
1978                                                 throw new ArgumentOutOfRangeException ("index");
1979
1980                                         return object_items[index];
1981                                 }
1982                                 set {
1983                                         if (index < 0 || index >= Count)
1984                                                 throw new ArgumentOutOfRangeException ("index");
1985                                         if (value == null)
1986                                                 throw new ArgumentNullException ("value");
1987
1988 #if NET_2_0
1989                                         //UIA Framework event: Item Removed
1990                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, index));
1991 #endif
1992
1993                                         object_items[index] = value;
1994                                         
1995 #if NET_2_0
1996                                         //UIA Framework event: Item Added
1997                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
1998 #endif
1999
2000                                         if (owner.listbox_ctrl != null)
2001                                                 owner.listbox_ctrl.InvalidateItem (index);
2002                                         if (index == owner.SelectedIndex) {
2003                                                 if (owner.textbox_ctrl == null)
2004                                                         owner.Refresh ();
2005                                                 else
2006                                                         owner.textbox_ctrl.SelectedText = value.ToString ();
2007                                         }
2008                                 }
2009                         }
2010
2011                         bool ICollection.IsSynchronized {
2012                                 get { return false; }
2013                         }
2014
2015                         object ICollection.SyncRoot {
2016                                 get { return this; }
2017                         }
2018
2019                         bool IList.IsFixedSize {
2020                                 get { return false; }
2021                         }
2022
2023                         #endregion Public Properties
2024                         
2025                         #region Public Methods
2026                         public int Add (object item)
2027                         {
2028                                 int idx;
2029
2030                                 idx = AddItem (item);
2031                                 owner.UpdatedItems ();
2032                                 return idx;
2033                         }
2034
2035                         public void AddRange (object[] items)
2036                         {
2037                                 if (items == null)
2038                                         throw new ArgumentNullException ("items");
2039
2040                                 foreach (object mi in items)
2041                                         AddItem (mi);
2042                                         
2043                                 owner.UpdatedItems ();
2044                         }
2045
2046                         public void Clear ()
2047                         {
2048                                 owner.selected_index = -1;
2049                                 object_items.Clear ();
2050                                 owner.UpdatedItems ();
2051                                 owner.Refresh ();
2052                                 
2053 #if NET_2_0
2054                                 //UIA Framework event: Items list cleared
2055                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, -1));
2056 #endif
2057                         }
2058                         
2059                         public bool Contains (object value)
2060                         {
2061                                 if (value == null)
2062                                         throw new ArgumentNullException ("value");
2063
2064                                 return object_items.Contains (value);
2065                         }
2066
2067 #if NET_2_0
2068                         public void CopyTo (object [] destination, int arrayIndex)
2069                         {
2070                                 object_items.CopyTo (destination, arrayIndex);
2071                         }
2072
2073                         void ICollection.CopyTo (Array destination, int index)
2074                         {
2075                                 object_items.CopyTo (destination, index);
2076                         }
2077 #else
2078                         public void CopyTo (object [] dest, int arrayIndex)
2079                         {
2080                                 object_items.CopyTo (dest, arrayIndex);
2081                         }
2082
2083                         void ICollection.CopyTo (Array dest, int index)
2084                         {
2085                                 object_items.CopyTo (dest, index);
2086                         }
2087 #endif
2088
2089                         public IEnumerator GetEnumerator ()
2090                         {
2091                                 return object_items.GetEnumerator ();
2092                         }
2093
2094                         int IList.Add (object item)
2095                         {
2096                                 return Add (item);
2097                         }
2098
2099                         public int IndexOf (object value)
2100                         {
2101                                 if (value == null)
2102                                         throw new ArgumentNullException ("value");
2103
2104                                 return object_items.IndexOf (value);
2105                         }
2106
2107                         public void Insert (int index,  object item)
2108                         {
2109                                 if (index < 0 || index > Count)
2110                                         throw new ArgumentOutOfRangeException ("index");
2111                                 if (item == null)
2112                                         throw new ArgumentNullException ("item");
2113                                 
2114                                 owner.BeginUpdate ();
2115                                 
2116                                 if (owner.Sorted)
2117                                         AddItem (item);
2118                                 else {
2119                                         object_items.Insert (index, item);
2120 #if NET_2_0
2121                                         //UIA Framework event: Item added
2122                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2123 #endif                                  
2124                                 }
2125                                 
2126                                 owner.EndUpdate ();     // Calls UpdatedItems
2127                         }
2128
2129                         public void Remove (object value)
2130                         {
2131                                 if (value == null)
2132                                         return;
2133
2134                                 if (IndexOf (value) == owner.SelectedIndex)
2135                                         owner.SelectedIndex = -1;
2136                                 
2137                                 RemoveAt (IndexOf (value));
2138                         }
2139
2140                         public void RemoveAt (int index)
2141                         {
2142                                 if (index < 0 || index >= Count)
2143                                         throw new ArgumentOutOfRangeException ("index");
2144                                         
2145                                 if (index == owner.SelectedIndex)
2146                                         owner.SelectedIndex = -1;
2147
2148                                 object_items.RemoveAt (index);
2149                                 owner.UpdatedItems ();
2150                                 
2151 #if NET_2_0
2152                                 //UIA Framework event: Item removed
2153                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, index));
2154 #endif
2155                         }
2156                         #endregion Public Methods
2157
2158                         #region Private Methods
2159                         private int AddItem (object item)
2160                         {
2161                                 if (item == null)
2162                                         throw new ArgumentNullException ("item");
2163
2164                                 if (owner.Sorted) {
2165                                         int index = 0;
2166                                         foreach (object o in object_items) {
2167                                                 if (String.Compare (item.ToString (), o.ToString ()) < 0) {
2168                                                         object_items.Insert (index, item);
2169                                                         
2170                                                         // If we added the new item before the selectedindex
2171                                                         // bump the selectedindex by one, behavior differs if
2172                                                         // Handle has not been created.
2173                                                         if (index <= owner.selected_index && owner.IsHandleCreated)
2174                                                                 owner.selected_index++;
2175                                                                 
2176 #if NET_2_0
2177                                                         //UIA Framework event: Item added
2178                                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2179 #endif
2180
2181                                                         return index;
2182                                                 }
2183                                                 index++;
2184                                         }
2185                                 }
2186                                 object_items.Add (item);
2187                                 
2188 #if NET_2_0
2189                                 //UIA Framework event: Item added
2190                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, object_items.Count - 1));
2191 #endif
2192                                 
2193                                 return object_items.Count - 1;
2194                         }
2195                         
2196                         internal void AddRange (IList items)
2197                         {
2198                                 foreach (object mi in items)
2199                                         AddItem (mi);
2200                                 
2201                                 owner.UpdatedItems ();
2202                         }
2203
2204                         internal void Sort ()
2205                         {
2206                                 object_items.Sort ();
2207                         }
2208
2209                         #endregion Private Methods
2210                 }
2211
2212                 internal class ComboTextBox : TextBox {
2213
2214                         private ComboBox owner;
2215
2216                         public ComboTextBox (ComboBox owner)
2217                         {
2218                                 this.owner = owner;
2219                                 ShowSelection = false;
2220                                 HideSelection = false;
2221                         }
2222
2223                         internal void SetSelectable (bool selectable)
2224                         {
2225                                 SetStyle (ControlStyles.Selectable, selectable);
2226                         }
2227
2228                         internal void ActivateCaret (bool active)
2229                         {
2230                                 if (active)
2231                                         document.CaretHasFocus ();
2232                                 else
2233                                         document.CaretLostFocus ();
2234                         }
2235                         
2236 #if NET_2_0
2237                         internal override void OnTextUpdate ()
2238                         {
2239                                 base.OnTextUpdate ();
2240                                 owner.OnTextUpdate (EventArgs.Empty);
2241                         }
2242 #endif
2243                         
2244                         protected override void OnGotFocus (EventArgs e)
2245                         {
2246                                 owner.Select (false, true);
2247                         }
2248
2249                         protected override void OnLostFocus (EventArgs e)
2250                         {
2251                                 owner.Select (false, true);
2252                         }
2253
2254                         public override bool Focused {
2255                                 get {
2256                                         return owner.Focused;
2257                                 }
2258                         }
2259                         
2260                         internal override bool ActivateOnShow { get { return false; } }
2261                 }
2262
2263                 internal class ComboListBox : Control
2264                 {
2265                         private ComboBox owner;
2266                         private VScrollBarLB vscrollbar_ctrl;
2267                         private int top_item;                   /* First item that we show the in the current page */
2268                         private int last_item;                  /* Last visible item */
2269                         internal int page_size;                 /* Number of listbox items per page */
2270                         private Rectangle textarea_drawable;    /* Rectangle of the drawable text area */
2271                         
2272                         internal enum ItemNavigation
2273                         {
2274                                 First,
2275                                 Last,
2276                                 Next,
2277                                 Previous,
2278                                 NextPage,
2279                                 PreviousPage,
2280                         }
2281                         
2282                         class VScrollBarLB : VScrollBar
2283                         {
2284                                 public VScrollBarLB ()
2285                                 {
2286                                 }
2287                                 
2288                                 internal override bool InternalCapture {
2289                                         get { return Capture; }
2290                                         set { }
2291                                 }
2292
2293                                 public void FireMouseDown (MouseEventArgs e) 
2294                                 {
2295                                         if (!Visible) 
2296                                                 return;
2297
2298                                         e = TranslateEvent (e);
2299                                         OnMouseDown (e);
2300                                 }
2301                                 
2302                                 public void FireMouseUp (MouseEventArgs e) 
2303                                 {
2304                                         if (!Visible)
2305                                                 return;
2306
2307                                         e = TranslateEvent (e);
2308                                         OnMouseUp (e);
2309                                 }
2310                                 
2311                                 public void FireMouseMove (MouseEventArgs e) 
2312                                 {
2313                                         if (!Visible)
2314                                                 return;
2315
2316                                         e = TranslateEvent (e);
2317                                         OnMouseMove (e);
2318                                 }
2319                                 
2320                                 MouseEventArgs TranslateEvent (MouseEventArgs e)
2321                                 {
2322                                         Point loc = PointToClient (Control.MousePosition);
2323                                         return new MouseEventArgs (e.Button, e.Clicks, loc.X, loc.Y, e.Delta);
2324                                 }
2325                         }
2326
2327                         public ComboListBox (ComboBox owner)
2328                         {
2329                                 this.owner = owner;
2330                                 top_item = 0;
2331                                 last_item = 0;
2332                                 page_size = 0;
2333
2334                                 MouseWheel += new MouseEventHandler (OnMouseWheelCLB);
2335
2336                                 SetStyle (ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
2337                                 SetStyle (ControlStyles.ResizeRedraw | ControlStyles.Opaque, true);
2338
2339                                 this.is_visible = false;
2340
2341                                 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2342                                         InternalBorderStyle = BorderStyle.Fixed3D;
2343                                 else
2344                                         InternalBorderStyle = BorderStyle.FixedSingle;
2345                         }
2346
2347                         protected override CreateParams CreateParams
2348                         {
2349                                 get {
2350                                         CreateParams cp = base.CreateParams;
2351                                         if (owner == null || owner.DropDownStyle == ComboBoxStyle.Simple)
2352                                                 return cp;
2353
2354                                         cp.Style ^= (int)WindowStyles.WS_CHILD;
2355                                         cp.Style ^= (int)WindowStyles.WS_VISIBLE;
2356                                         cp.Style |= (int)WindowStyles.WS_POPUP;
2357                                         cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW | (int) WindowExStyles.WS_EX_TOPMOST;
2358                                         return cp;
2359                                 }
2360                         }
2361
2362                         internal override bool InternalCapture {
2363                                 get {
2364                                         return Capture;
2365                                 }
2366
2367                                 set {
2368                                 }
2369                         }
2370
2371                         internal override bool ActivateOnShow { get { return false; } }
2372                         #region Private Methods
2373
2374                         // Calcs the listbox area
2375                         internal void CalcListBoxArea ()
2376                         {
2377                                 int width, height;
2378                                 bool show_scrollbar = false;
2379
2380                                 if (owner.DropDownStyle == ComboBoxStyle.Simple) {
2381                                         Rectangle area = owner.listbox_area;
2382                                         width = area.Width;
2383                                         height = area.Height;
2384
2385                                         // No calculation needed
2386                                         if (height <= 0 || width <= 0)
2387                                                 return;
2388                                 }
2389                                 else { // DropDown or DropDownList
2390                                         
2391                                         width = owner.DropDownWidth;
2392                                         int count = (owner.Items.Count <= owner.MaxDropDownItems) ? owner.Items.Count : owner.MaxDropDownItems;
2393                                         
2394                                         if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2395                                                 height = 0;
2396                                                 for (int i = 0; i < count; i++) {
2397                                                         height += owner.GetItemHeight (i);
2398                                                 }
2399                                                 
2400                                         } else  {
2401 #if NET_2_0
2402                                                 height = owner.DropDownHeight;
2403 #else           
2404                                                 height = owner.ItemHeight * count;
2405 #endif
2406                                         }
2407                                 }
2408                                 
2409                                 page_size = Math.Max (height / owner.ItemHeight, 1);
2410
2411                                 ComboBoxStyle dropdown_style = owner.DropDownStyle;
2412                                 if ((dropdown_style != ComboBoxStyle.Simple && owner.Items.Count <= owner.MaxDropDownItems)
2413                                         || (dropdown_style == ComboBoxStyle.Simple && owner.Items.Count * owner.ItemHeight < height)) {
2414
2415                                         if (vscrollbar_ctrl != null)
2416                                                 vscrollbar_ctrl.Visible = false;
2417                                         if (dropdown_style != ComboBoxStyle.Simple)
2418                                                 height = owner.ItemHeight * owner.items.Count;
2419                                 } else {
2420                                         /* Need vertical scrollbar */
2421                                         if (vscrollbar_ctrl == null) {
2422                                                 vscrollbar_ctrl = new VScrollBarLB ();
2423                                                 vscrollbar_ctrl.Minimum = 0;
2424                                                 vscrollbar_ctrl.SmallChange = 1;
2425                                                 vscrollbar_ctrl.LargeChange = 1;
2426                                                 vscrollbar_ctrl.Maximum = 0;
2427                                                 vscrollbar_ctrl.ValueChanged += new EventHandler (VerticalScrollEvent);
2428                                                 Controls.AddImplicit (vscrollbar_ctrl);
2429                                         }
2430                                         
2431                                         vscrollbar_ctrl.Dock = DockStyle.Right;
2432
2433                                         vscrollbar_ctrl.Maximum = owner.Items.Count - 1;
2434 #if NET_2_0
2435                                         int large = page_size;
2436 #else
2437                                         int large = (dropdown_style == ComboBoxStyle.Simple ? page_size : owner.maxdrop_items) - 1;
2438 #endif
2439                                         if (large < 1)
2440                                                 large = 1;
2441                                         vscrollbar_ctrl.LargeChange = large;
2442                                         show_scrollbar = vscrollbar_ctrl.Visible = true;
2443
2444                                         int hli = HighlightedIndex;
2445                                         if (hli > 0) {
2446                                                 hli = Math.Min (hli, vscrollbar_ctrl.Maximum);
2447                                                 vscrollbar_ctrl.Value = hli;
2448                                         }
2449                                 }
2450                                 
2451                                 Size = new Size (width, height);
2452                                 textarea_drawable = ClientRectangle;
2453                                 textarea_drawable.Width = width;
2454                                 textarea_drawable.Height = height;
2455                                 
2456                                 if (vscrollbar_ctrl != null && show_scrollbar)
2457                                         textarea_drawable.Width -= vscrollbar_ctrl.Width;
2458
2459                                 last_item = LastVisibleItem ();
2460                         }
2461
2462                         private void Draw (Rectangle clip, Graphics dc)
2463                         {
2464                                 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (owner.BackColor), clip);
2465
2466                                 if (owner.Items.Count > 0) {
2467                                         
2468                                         for (int i = top_item; i <= last_item; i++) {
2469                                                 Rectangle item_rect = GetItemDisplayRectangle (i, top_item);
2470
2471                                                 if (!clip.IntersectsWith (item_rect))
2472                                                         continue;
2473
2474                                                 DrawItemState state = DrawItemState.None;
2475
2476                                                 if (i == HighlightedIndex) {
2477                                                         state |= DrawItemState.Selected;
2478                                                         
2479                                                         if (owner.DropDownStyle == ComboBoxStyle.DropDownList) {
2480                                                                 state |= DrawItemState.Focus;
2481                                                         }
2482                                                 }
2483                                                 
2484                                                 owner.OnDrawItem (new DrawItemEventArgs (dc, owner.Font, item_rect,
2485                                                         i, state, owner.ForeColor, owner.BackColor));
2486                                         }
2487                                 }
2488                         }
2489
2490                         int highlighted_index = -1;
2491
2492                         public int HighlightedIndex {
2493                                 get { return highlighted_index; }
2494                                 set { 
2495                                         if (highlighted_index == value)
2496                                                 return;
2497
2498                                         if (highlighted_index != -1 && highlighted_index < this.owner.Items.Count)
2499                                                 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2500                                         highlighted_index = value;
2501                                         if (highlighted_index != -1)
2502                                                 Invalidate (GetItemDisplayRectangle (highlighted_index, top_item));
2503                                 }
2504                         }
2505
2506                         private Rectangle GetItemDisplayRectangle (int index, int top_index)
2507                         {
2508                                 if (index < 0 || index >= owner.Items.Count)
2509                                         throw new  ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
2510
2511                                 Rectangle item_rect = new Rectangle ();
2512                                 int height = owner.GetItemHeight (index);
2513
2514                                 item_rect.X = 0;
2515                                 item_rect.Width = textarea_drawable.Width;
2516                                 if (owner.DrawMode == DrawMode.OwnerDrawVariable) {
2517                                         item_rect.Y = 0;
2518                                         for (int i = top_index; i < index; i++)
2519                                                 item_rect.Y += owner.GetItemHeight (i);
2520                                 } else
2521                                         item_rect.Y = height * (index - top_index);
2522
2523                                 item_rect.Height = height;
2524                                 return item_rect;
2525                         }
2526
2527                         public void HideWindow ()
2528                         {
2529                                 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2530                                         return;
2531                                         
2532                                 Capture = false;
2533                                 Hide ();
2534                                 owner.DropDownListBoxFinished ();
2535                         }
2536
2537                         private int IndexFromPointDisplayRectangle (int x, int y)
2538                         {
2539                                 for (int i = top_item; i <= last_item; i++) {
2540                                         if (GetItemDisplayRectangle (i, top_item).Contains (x, y) == true)
2541                                                 return i;
2542                                 }
2543
2544                                 return -1;
2545                         }
2546
2547                         public void InvalidateItem (int index)
2548                         {
2549                                 if (Visible)
2550                                         Invalidate (GetItemDisplayRectangle (index, top_item));
2551                         }
2552
2553                         public int LastVisibleItem ()
2554                         {
2555                                 Rectangle item_rect;
2556                                 int top_y = textarea_drawable.Y + textarea_drawable.Height;
2557                                 int i = 0;
2558                                 
2559                                 for (i = top_item; i < owner.Items.Count; i++) {
2560                                         item_rect = GetItemDisplayRectangle (i, top_item);
2561                                         if (item_rect.Y + item_rect.Height > top_y) {
2562                                                 return i;
2563                                         }
2564                                 }
2565                                 return i - 1;
2566                         }
2567
2568                         public void SetTopItem (int item)
2569                         {
2570                                 if (top_item == item)
2571                                         return;
2572                                 top_item = item;
2573                                 UpdateLastVisibleItem ();
2574                                 Invalidate ();
2575                         }
2576
2577                         public int FirstVisibleItem ()
2578                         {
2579                                 return top_item;
2580                         }
2581                         
2582                         bool scrollbar_grabbed = false;
2583
2584                         bool InScrollBar {
2585                                 get {
2586                                         if (vscrollbar_ctrl == null || !vscrollbar_ctrl.is_visible)
2587                                                 return false;
2588
2589                                         return vscrollbar_ctrl.Bounds.Contains (PointToClient (Control.MousePosition));
2590                                 }
2591                         }
2592
2593                         protected override void OnMouseDown (MouseEventArgs e)
2594                         {
2595                                 if (InScrollBar) {
2596                                         vscrollbar_ctrl.FireMouseDown (e);
2597                                         scrollbar_grabbed = true;
2598                                 }
2599                         }
2600
2601                         protected override void OnMouseMove (MouseEventArgs e)
2602                         {
2603                                 if (owner.DropDownStyle == ComboBoxStyle.Simple)
2604                                         return;
2605
2606                                 if (scrollbar_grabbed || (!Capture && InScrollBar)) {
2607                                         vscrollbar_ctrl.FireMouseMove (e);
2608                                         return;
2609                                 }
2610
2611                                 Point pt = PointToClient (Control.MousePosition);
2612                                 int index = IndexFromPointDisplayRectangle (pt.X, pt.Y);
2613
2614                                 if (index != -1)
2615                                         HighlightedIndex = index;
2616                         }
2617                         
2618                         protected override void OnMouseUp (MouseEventArgs e)
2619                         {
2620                                 int index = IndexFromPointDisplayRectangle (e.X, e.Y);
2621
2622                                 if (scrollbar_grabbed) {
2623                                         vscrollbar_ctrl.FireMouseUp (e);
2624                                         scrollbar_grabbed = false;
2625                                         if (index != -1)
2626                                                 HighlightedIndex = index;
2627                                         return;
2628                                 }
2629
2630                                 if (index == -1) {
2631                                         HideWindow ();
2632                                         return;
2633                                 }
2634
2635                                 owner.SelectedIndex = index;
2636                                 owner.OnSelectionChangeCommitted (new EventArgs ());
2637                                 HideWindow ();
2638                         }
2639
2640                         internal override void OnPaintInternal (PaintEventArgs pevent)
2641                         {
2642                                 Draw (pevent.ClipRectangle,pevent.Graphics);
2643                         }
2644
2645                         public bool ShowWindow ()
2646                         {
2647                                 if (owner.DropDownStyle == ComboBoxStyle.Simple && owner.Items.Count == 0)
2648                                         return false;
2649
2650                                 HighlightedIndex = owner.SelectedIndex;
2651
2652                                 CalcListBoxArea ();
2653                                 Show ();
2654
2655                                 Refresh ();
2656                                 owner.OnDropDown (EventArgs.Empty);
2657                                 return true;
2658                         }
2659                         
2660                         public void UpdateLastVisibleItem ()
2661                         {
2662                                 last_item = LastVisibleItem ();
2663                         }
2664
2665                         public void Scroll (int delta)
2666                         {
2667                                 if (delta == 0 || vscrollbar_ctrl == null || !vscrollbar_ctrl.Visible)
2668                                         return;
2669
2670                                 int max = vscrollbar_ctrl.Maximum - page_size + 1;
2671
2672                                 int val = vscrollbar_ctrl.Value + delta;
2673                                 if (val > max)
2674                                         val = max;
2675                                 else if (val < vscrollbar_ctrl.Minimum)
2676                                         val = vscrollbar_ctrl.Minimum;
2677                                 vscrollbar_ctrl.Value = val;
2678                         }
2679
2680                         private void OnMouseWheelCLB (object sender, MouseEventArgs me)
2681                         {
2682                                 if (owner.Items.Count == 0)
2683                                         return;
2684
2685                                 int lines = me.Delta / 120 * SystemInformation.MouseWheelScrollLines;
2686                                 Scroll (-lines);
2687                         }
2688
2689                         // Value Changed
2690                         private void VerticalScrollEvent (object sender, EventArgs e)
2691                         {
2692                                 if (top_item == vscrollbar_ctrl.Value)
2693                                         return;
2694
2695                                 top_item =  vscrollbar_ctrl.Value;
2696                                 UpdateLastVisibleItem ();
2697                                 Invalidate ();
2698                         }
2699                         
2700                         protected override void WndProc(ref Message m) {
2701                                 if (m.Msg == (int)Msg.WM_SETFOCUS) {
2702                                         owner.Select (false, true);
2703                                 }
2704                                 base.WndProc (ref m);
2705                         }
2706
2707                         #endregion Private Methods
2708                 }
2709         }
2710 }