* XplatUIWin32.cs: When faking styles don't remove the WS_VISIBLE flag.
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Form.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 //      Peter Bartok    pbartok@novell.com
24 //
25
26 // NOT COMPLETE
27
28 using System;
29 using System.Drawing;
30 using System.ComponentModel;
31 using System.ComponentModel.Design;
32 using System.ComponentModel.Design.Serialization;
33 using System.Collections;
34 using System.Runtime.InteropServices;
35 using System.Threading;
36
37 namespace System.Windows.Forms {
38         [DesignerCategory("Form")]
39         [DesignTimeVisible(false)]
40         [Designer("System.Windows.Forms.Design.FormDocumentDesigner, " + Consts.AssemblySystem_Design, typeof(IRootDesigner))]
41         [DefaultEvent("Load")]
42 #if NET_2_0
43         [ClassInterface (ClassInterfaceType.AutoDispatch)]
44         [InitializationEvent ("Load")]
45         [ComVisible (true)]
46 #endif
47         [ToolboxItem(false)]
48         public class Form : ContainerControl {
49                 #region Local Variables
50                 internal bool                   closing;
51                 FormBorderStyle                 form_border_style;
52                 private bool                    autoscale;
53                 private Size                    clientsize_set;
54                 private Size                    autoscale_base_size;
55                 private bool                    allow_transparency;
56                 private static Icon             default_icon;
57                 internal bool                   is_modal;
58                 internal FormWindowState        window_state;
59                 private bool                    control_box;
60                 private bool                    minimize_box;
61                 private bool                    maximize_box;
62                 private bool                    help_button;
63                 private bool                    show_in_taskbar;
64                 private bool                    topmost;
65                 private IButtonControl          accept_button;
66                 private IButtonControl          cancel_button;
67                 private DialogResult            dialog_result;
68                 private FormStartPosition       start_position;
69                 private Form                    owner;
70                 private Form.ControlCollection  owned_forms;
71                 private MdiClient               mdi_container;
72                 internal InternalWindowManager  window_manager;
73                 private Form                    mdi_parent;
74                 private bool                    key_preview;
75                 private MainMenu                menu;
76                 private Icon                    icon;
77                 private Size                    maximum_size;
78                 private Size                    minimum_size;
79                 private SizeGripStyle           size_grip_style;
80                 private SizeGrip                size_grip;
81                 private Rectangle               maximized_bounds;
82                 private Rectangle               default_maximized_bounds;
83                 private double                  opacity;
84                 internal ApplicationContext     context;
85                 Color                           transparency_key;
86                 internal MenuTracker            active_tracker;
87                 private bool                    is_loaded;
88                 internal bool                   is_changing_visible_state;
89                 internal bool                   has_been_visible;
90
91 #if NET_2_0
92                 private MenuStrip               main_menu_strip;
93                 private bool                    show_icon = true;
94                 private bool                    shown_raised;  // The shown event is only raised once
95 #endif
96                 #endregion      // Local Variables
97
98                 #region Private & Internal Methods
99                 static Form ()
100                 {
101                         default_icon = Locale.GetResource("mono.ico") as Icon;
102                 }
103
104                 // warning: this is only hooked up when an mdi container is created.
105                 private void ControlAddedHandler (object sender, ControlEventArgs e)
106                 {
107                         if (mdi_container != null) {
108                                 mdi_container.SendToBack ();
109                         }
110                 }
111
112                 // Convenience method for fire BOTH OnClosing and OnFormClosing events
113                 // Returns the value of Cancel, so true means the Close was cancelled,
114                 // and you shouldn't close the form.
115                 internal bool FireClosingEvents (CloseReason reason)
116                 {
117                         CancelEventArgs cea = new CancelEventArgs ();
118                         this.OnClosing (cea);
119                         
120 #if NET_2_0
121                         FormClosingEventArgs fcea = new FormClosingEventArgs (reason, cea.Cancel);
122                         this.OnFormClosing (fcea);
123                         return fcea.Cancel;
124 #else
125                         return cea.Cancel;
126 #endif
127                 }
128                 
129                 private void SelectActiveControl ()
130                 {
131                         if (this.IsMdiContainer) {
132                                 mdi_container.SendFocusToActiveChild ();
133                                 return;
134                         }
135                                 
136                         if (this.ActiveControl == null) {
137                                 bool visible;
138
139                                 // This visible hack is to work around CanSelect always being false if one of the parents
140                                 // is not visible; and we by default create Form invisible...
141                                 visible = this.is_visible;
142                                 this.is_visible = true;
143
144                                 if (SelectNextControl (this, true, true, true, true) == false) {
145                                         Select (this);
146                                 }
147
148                                 this.is_visible = visible;
149                         } else {
150                                 Select (ActiveControl);
151                         }
152                 }
153                 
154                 private new void UpdateSizeGripVisible ()
155                 {
156                         // Following link explains when to show size grip:
157                         // http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=138687&SiteID=1
158                         // if SizeGripStyle.Auto, only shown if form is shown using ShowDialog and is sizable
159                         // if SizeGripStyle.Show, only shown if form is sizable
160                         
161                         bool show = false;
162                         
163                         switch (size_grip_style) {
164                         case SizeGripStyle.Auto:
165                                 show = is_modal && (form_border_style == FormBorderStyle.Sizable || form_border_style == FormBorderStyle.SizableToolWindow);
166                                 break;
167                         case SizeGripStyle.Hide:
168                                 show = false;
169                                 break;
170                         case SizeGripStyle.Show:
171                                 show = (form_border_style == FormBorderStyle.Sizable || form_border_style == FormBorderStyle.SizableToolWindow);
172                                 break;
173                         }
174                         
175                         if (!show) {
176                                 if (size_grip != null && size_grip.Visible)
177                                         size_grip.Visible = false;
178                         } else {
179                                 if (size_grip == null) {
180                                         size_grip = new SizeGrip (this);
181                                         size_grip.Virtual = true;
182                                         size_grip.FillBackground = false;
183                                 }
184                                 size_grip.Visible = true;
185                         }
186                 }
187                 
188                 internal void ChangingParent (Control new_parent)
189                 {
190                         if (IsMdiChild) {
191                                 return;
192                         }
193                         
194                         if (new_parent == null) {
195                                 window_manager = null;
196                         } else if (new_parent is MdiClient) {
197                                 window_manager = new MdiWindowManager (this, (MdiClient) new_parent);
198                         } else {
199                                 window_manager = new FormWindowManager (this);
200                                 if (IsHandleCreated) {
201                                         XplatUI.SetWindowStyle (Handle, CreateParams);
202                                 }
203                         }
204                 
205                         if (window_manager != null) {
206                                 window_manager.UpdateWindowState (window_state, window_state, true);
207                         }
208                 }
209                 #endregion      // Private & Internal Methods
210
211                 #region Public Classes
212 #if NET_2_0
213                 [ComVisible (false)]
214 #endif          
215                 public new class ControlCollection : Control.ControlCollection {
216                         Form    form_owner;
217
218                         public ControlCollection(Form owner) : base(owner) {
219                                 this.form_owner = owner;
220                         }
221
222                         public override void Add(Control value) {
223                                 if (Contains (value))
224                                         return;
225                                 AddToList (value);
226                                 ((Form)value).owner=form_owner;
227                         }
228
229                         public override void Remove(Control value) {
230                                 ((Form)value).owner = null;
231                                 base.Remove (value);
232                         }
233                 }
234                 #endregion      // Public Classes
235
236                 #region Public Constructor & Destructor
237                 public Form ()
238                 {
239                         SizeF current_scale = GetAutoScaleSize (DeviceContext, Font);
240
241                         autoscale = true;
242                         autoscale_base_size = new Size ((int)current_scale.Width, (int) current_scale.Height);
243                         allow_transparency = false;
244                         closing = false;
245                         is_modal = false;
246                         dialog_result = DialogResult.None;
247                         start_position = FormStartPosition.WindowsDefaultLocation;
248                         form_border_style = FormBorderStyle.Sizable;
249                         window_state = FormWindowState.Normal;
250                         key_preview = false;
251                         opacity = 1D;
252                         menu = null;
253                         icon = default_icon;
254                         minimum_size = Size.Empty;
255                         maximum_size = Size.Empty;
256                         clientsize_set = Size.Empty;
257                         control_box = true;
258                         minimize_box = true;
259                         maximize_box = true;
260                         help_button = false;
261                         show_in_taskbar = true;
262                         is_visible = false;
263                         is_toplevel = true;
264                         size_grip_style = SizeGripStyle.Auto;
265                         maximized_bounds = Rectangle.Empty;
266                         default_maximized_bounds = Rectangle.Empty;
267                         owned_forms = new Form.ControlCollection(this);
268                         transparency_key = Color.Empty;
269
270                         // FIXME: this should disappear just as soon as the handle creation is done in the right place (here is too soon()
271                         UpdateBounds();
272
273                 }
274                 #endregion      // Public Constructor & Destructor
275
276                 #region Public Static Properties
277
278                 public static Form ActiveForm {
279                         get {
280                                 Control active;
281
282                                 active = FromHandle(XplatUI.GetActive());
283
284                                 if (active != null) {
285                                         if ( !(active is Form)) {
286                                                 Control parent;
287
288                                                 parent = active.Parent;
289                                                 while (parent != null) {
290                                                         if (parent is Form) {
291                                                                 return (Form)parent;
292                                                         }
293                                                         parent = parent.Parent;
294                                                 }
295                                         } else {
296                                                 return (Form)active;
297                                         }
298                                 }
299                                 return null;
300                         }
301                 }
302
303                 #endregion      // Public Static Properties
304
305                 #region Public Instance Properties
306                 [DefaultValue(null)]
307                 public IButtonControl AcceptButton {
308                         get {
309                                 return accept_button;
310                         }
311
312                         set {
313                                 accept_button = value;
314                                 CheckAcceptButton();
315                         }
316                 }
317
318                 [Browsable(false)]
319                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
320                 public bool AllowTransparency {
321                         get {
322                                 return allow_transparency;
323                         }
324
325                         set {
326                                 if (value == allow_transparency) {
327                                         return;
328                                 }
329
330                                 allow_transparency = value;
331
332                                 if (value) {
333                                         if (IsHandleCreated) {
334                                                 if ((XplatUI.SupportsTransparency() & TransparencySupport.Set) != 0) {
335                                                         XplatUI.SetWindowTransparency(Handle, Opacity, TransparencyKey);
336                                                 }
337                                         } else {
338                                                 UpdateStyles(); // Remove the WS_EX_LAYERED style
339                                         }
340                                 }
341                         }
342                 }
343
344 #if NET_2_0
345                 [Browsable (false)]
346                 [EditorBrowsable (EditorBrowsableState.Never)]
347                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
348                 [Obsolete ("This property has been deprecated in favor of AutoScaleMode.")]
349 #else
350                 [DefaultValue(true)]
351 #endif
352                 [MWFCategory("Layout")]
353                 public bool AutoScale {
354                         get {
355                                 return autoscale;
356                         }
357
358                         set {
359                                 autoscale = value;
360                         }
361                 }
362
363 #if NET_2_0
364                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
365                 [EditorBrowsable(EditorBrowsableState.Never)]
366 #else
367                 [EditorBrowsable(EditorBrowsableState.Advanced)]
368 #endif
369                 [Localizable(true)]
370                 [Browsable(false)]
371                 public virtual Size AutoScaleBaseSize {
372                         get {
373                                 return autoscale_base_size;
374                         }
375
376                         set {
377                                 autoscale_base_size = value;
378                         }
379                 }
380
381                 [Localizable(true)]
382                 public override bool AutoScroll {
383                         get {
384                                 return base.AutoScroll;
385                         }
386                         set {
387                                 base.AutoScroll = value;
388                         }
389                 }
390
391                 public override Color BackColor {
392                         get {
393                                 /* we don't let parents override our
394                                  default background color for forms.
395                                  this fixes the default color for mdi
396                                  children. */
397                                 if (background_color.IsEmpty)
398                                         return DefaultBackColor;
399                                 else
400                                         return background_color;
401                         }
402                         set {
403                                 base.BackColor = value;
404                         }
405                 }
406
407                 [DefaultValue(null)]
408                 public IButtonControl CancelButton {
409                         get {
410                                 return cancel_button;
411                         }
412
413                         set {
414                                 cancel_button = value;
415                                 if (cancel_button != null && cancel_button.DialogResult == DialogResult.None)
416                                         cancel_button.DialogResult = DialogResult.Cancel;
417                         }
418                 }
419
420                 // new property so we can change the DesignerSerializationVisibility
421                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
422                 [Localizable(true)]
423                 public new Size ClientSize {
424                         get { return base.ClientSize; }
425                         set { base.ClientSize = value; }
426                 }
427
428                 [DefaultValue(true)]
429                 [MWFCategory("Window Style")]
430                 public bool ControlBox {
431                         get {
432                                 return control_box;
433                         }
434
435                         set {
436                                 if (control_box != value) {
437                                         control_box = value;
438                                         UpdateStyles();
439                                 }
440                         }
441                 }
442
443                 [Browsable(false)]
444                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
445                 public Rectangle DesktopBounds {
446                         get {
447                                 return new Rectangle(Location, Size);
448                         }
449
450                         set {
451                                 Bounds = value;
452                         }
453                 }
454
455                 [Browsable(false)]
456                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
457                 public Point DesktopLocation {
458                         get {
459                                 return Location;
460                         }
461
462                         set {
463                                 Location = value;
464                         }
465                 }
466
467                 [Browsable(false)]
468                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
469                 public DialogResult DialogResult {
470                         get {
471                                 return dialog_result;
472                         }
473
474                         set {
475                                 if (value < DialogResult.None || value > DialogResult.No)
476                                         throw new InvalidEnumArgumentException ("value", (int) value, 
477                                                         typeof (DialogResult));
478
479                                 dialog_result = value;
480                                 closing = (dialog_result != DialogResult.None && is_modal);
481                         }
482                 }
483
484                 [DefaultValue(FormBorderStyle.Sizable)]
485                 [DispId(-504)]
486                 [MWFCategory("Appearance")]
487                 public FormBorderStyle FormBorderStyle {
488                         get {
489                                 return form_border_style;
490                         }
491                         set {
492                                 form_border_style = value;
493
494                                 if (window_manager == null) {
495                                         if (IsHandleCreated) {
496                                                 XplatUI.SetBorderStyle(window.Handle, form_border_style);
497                                         }
498                                 } else {
499                                         window_manager.UpdateBorderStyle (value);
500                                 }
501
502                                 UpdateStyles();
503                                 
504                                 if (this.Visible) 
505                                         this.Size = SizeFromClientSize (this.ClientSize);
506                                 else
507                                         XplatUI.InvalidateNC (this.Handle);
508                         }
509                 }
510
511                 [DefaultValue(false)]
512                 [MWFCategory("Window Style")]
513                 public bool HelpButton {
514                         get {
515                                 return help_button;
516                         }
517
518                         set {
519                                 if (help_button != value) {
520                                         help_button = value;
521                                         UpdateStyles();
522                                 }
523                         }
524                 }
525
526                 [Localizable(true)]
527                 [AmbientValue(null)]
528                 [MWFCategory("Window Style")]
529                 public Icon Icon {
530                         get {
531                                 return icon;
532                         }
533
534                         set {
535                                 if (icon != value) {
536                                         icon = value;
537
538                                         if (IsHandleCreated) {
539                                                 XplatUI.SetIcon(Handle, icon == null ? default_icon : icon);
540                                         }
541                                 }
542                         }
543                 }
544
545                 [Browsable(false)]
546                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
547                 public bool IsMdiChild {
548                         get {
549                                 return mdi_parent != null;
550                         }
551                 }
552
553                 [DefaultValue(false)]
554                 [MWFCategory("Window Style")]
555                 public bool IsMdiContainer {
556                         get {
557                                 return mdi_container != null;
558                         }
559
560                         set {
561                                 if (value && mdi_container == null) {
562                                         mdi_container = new MdiClient ();
563                                         Controls.Add(mdi_container);
564                                         ControlAdded += new ControlEventHandler (ControlAddedHandler);
565                                         mdi_container.SendToBack ();
566                                         mdi_container.SetParentText (true);
567                                 } else if (!value && mdi_container != null) {
568                                         Controls.Remove(mdi_container);
569                                         mdi_container = null;
570                                 }
571                         }
572                 }
573
574                 [Browsable(false)]
575                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
576                 public Form ActiveMdiChild {
577                         get {
578                                 if (!IsMdiContainer)
579                                         return null;
580                                 return (Form) mdi_container.ActiveMdiChild;
581                         }
582                 }
583
584                 [Browsable(false)]
585                 [EditorBrowsable(EditorBrowsableState.Advanced)]
586                 public bool IsRestrictedWindow {
587                         get {
588                                 return false;
589                         }
590                 }
591
592                 [DefaultValue(false)]
593                 public bool KeyPreview {
594                         get {
595                                 return key_preview;
596                         }
597
598                         set {
599                                 key_preview = value;
600                         }
601                 }
602
603 #if NET_2_0
604                 [DefaultValue (null)]
605                 [TypeConverter (typeof (ReferenceConverter))]
606                 public MenuStrip MainMenuStrip {
607                         get { return this.main_menu_strip; }
608                         set { 
609                                 if (this.main_menu_strip != value) {
610                                         this.main_menu_strip = value;
611                                         this.main_menu_strip.RefreshMdiItems ();
612                                 }
613                         }
614                 }
615                 
616                 [EditorBrowsable (EditorBrowsableState.Never)]
617                 [Browsable (false)]
618                 public new Padding Margin {
619                         get { return base.Margin; }
620                         set { base.Margin = value; }
621                 }
622 #endif
623
624                 [DefaultValue(true)]
625                 [MWFCategory("Window Style")]
626                 public bool MaximizeBox {
627                         get {
628                                 return maximize_box;
629                         }
630                         set {
631                                 if (maximize_box != value) {
632                                         maximize_box = value;
633                                         if (IsHandleCreated) {
634                                                 RecreateHandle();
635                                         }
636                                         UpdateStyles();
637                                 }
638                         }
639                 }
640
641                 [DefaultValue("{Width=0, Height=0}")]
642                 [Localizable(true)]
643                 [RefreshProperties(RefreshProperties.Repaint)]
644                 [MWFCategory("Layout")]
645                 public
646 #if NET_2_0
647                 override
648 #endif
649                 Size MaximumSize {
650                         get {
651                                 return maximum_size;
652                         }
653
654                         set {
655                                 if (maximum_size != value) {
656                                         maximum_size = value;
657                                         OnMaximumSizeChanged(EventArgs.Empty);
658                                         if (IsHandleCreated) {
659                                                 XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
660                                         }
661                                 }
662                         }
663                 }
664
665                 [Browsable(false)]
666                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
667                 public Form[] MdiChildren {
668                         get {
669                                 if (mdi_container != null)
670                                         return mdi_container.MdiChildren;
671                                 else
672                                         return new Form[0];
673                         }
674                 }
675
676                 [Browsable(false)]
677                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
678                 public Form MdiParent {
679                         get {
680                                 return mdi_parent;
681                         }
682
683                         set {
684                                 if (value != null && !value.IsMdiContainer)
685                                         throw new ArgumentException ("Form that was specified to be "
686                                                 + "the MdiParent for this form is not an MdiContainer.");
687
688                                 if (mdi_parent != null) {
689                                         mdi_parent.MdiContainer.Controls.Remove (this);
690                                 }
691
692                                 if (value != null) {
693                                         mdi_parent = value;
694                                         if (window_manager == null) {
695                                                 window_manager = new MdiWindowManager (this, mdi_parent.MdiContainer);
696                                         }
697                                         
698                                         mdi_parent.MdiContainer.Controls.Add (this);
699                                         mdi_parent.MdiContainer.Controls.SetChildIndex (this, 0);
700                                         
701                                         RecreateHandle ();
702                                 } else if (mdi_parent != null) {
703                                         mdi_parent = null;
704
705                                         // Create a new window manager
706                                         window_manager = null;
707                                         FormBorderStyle = form_border_style;
708
709                                         RecreateHandle ();
710                                 }
711                         }
712                 }
713
714                 internal MenuTracker ActiveTracker {
715                         get { return active_tracker; }
716                         set {
717                                 if (value == active_tracker)
718                                         return;
719
720                                 Capture = value != null;
721                                 active_tracker = value;
722                         }
723                 }
724
725                 internal MdiClient MdiContainer {
726                         get { return mdi_container; }
727                 }
728
729                 internal InternalWindowManager WindowManager {
730                         get { return window_manager; }
731                 }
732
733 #if NET_2_0
734                 [Browsable (false)]
735                 [TypeConverter (typeof (ReferenceConverter))]
736 #endif
737                 [DefaultValue(null)]
738                 [MWFCategory("Window Style")]
739                 public MainMenu Menu {
740                         get {
741                                 return menu;
742                         }
743
744                         set {
745                                 if (menu != value) {
746                                         menu = value;
747
748                                         if (menu != null && !IsMdiChild) {
749                                                 menu.SetForm (this);
750
751                                                 if (IsHandleCreated) {
752                                                         XplatUI.SetMenu (window.Handle, menu);
753                                                 }
754
755                                                 if (clientsize_set != Size.Empty) {
756                                                         SetClientSizeCore(clientsize_set.Width, clientsize_set.Height);
757                                                 } else {
758                                                         UpdateBounds (bounds.X, bounds.Y, bounds.Width, bounds.Height, ClientSize.Width, ClientSize.Height - 
759                                                                 ThemeEngine.Current.CalcMenuBarSize (DeviceContext, menu, ClientSize.Width));
760                                                 }
761                                         } else
762                                                 UpdateBounds ();
763                                 }
764                         }
765                 }
766
767                 [Browsable(false)]
768                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
769                 [EditorBrowsable(EditorBrowsableState.Advanced)]
770                 public MainMenu MergedMenu {
771                         get {
772                                 if (!IsMdiChild || window_manager == null)
773                                         return null;
774                                 return ((MdiWindowManager) window_manager).MergedMenu;
775                         }
776                 }
777
778                 // This is the menu in display and being used because of merging this can
779                 // be different then the menu that is actually assosciated with the form
780                 internal MainMenu ActiveMenu {
781                         get {
782                                 if (IsMdiChild)
783                                         return null;
784
785                                 if (IsMdiContainer && mdi_container.Controls.Count > 0 &&
786                                                 ((Form) mdi_container.Controls [0]).WindowState == FormWindowState.Maximized) {
787                                         MdiWindowManager wm = (MdiWindowManager) ((Form) mdi_container.Controls [0]).WindowManager;
788                                         return wm.MaximizedMenu;
789                                 }
790
791                                 Form amc = ActiveMdiChild;
792                                 if (amc == null || amc.Menu == null)
793                                         return menu;
794                                 return amc.MergedMenu;
795                         }
796                 }
797
798                 internal MdiWindowManager ActiveMaximizedMdiChild {
799                         get {
800                                 Form child = ActiveMdiChild;
801                                 if (child == null)
802                                         return null;
803                                 if (child.WindowManager == null || child.window_state != FormWindowState.Maximized)
804                                         return null;
805                                 return (MdiWindowManager) child.WindowManager;
806                         }
807                 }
808
809                 [DefaultValue(true)]
810                 [MWFCategory("Window Style")]
811                 public bool MinimizeBox {
812                         get {
813                                 return minimize_box;
814                         }
815                         set {
816                                 if (minimize_box != value) {
817                                         minimize_box = value;
818                                         if (IsHandleCreated) {
819                                                 RecreateHandle();
820                                         }
821                                         UpdateStyles();
822                                 }
823                         }
824                 }
825
826 #if !NET_2_0
827                 [DefaultValue("{Width=0, Height=0}")]
828 #endif
829                 [Localizable(true)]
830                 [RefreshProperties(RefreshProperties.Repaint)]
831                 [MWFCategory("Layout")]
832                 public
833 #if NET_2_0
834                 override
835 #endif
836                 Size MinimumSize {
837                         get {
838                                 return minimum_size;
839                         }
840
841                         set {
842                                 if (minimum_size != value) {
843                                         minimum_size = value;
844
845                                         if ((Size.Width < value.Width) || (Size.Height < value.Height)) {
846                                                 Size = new Size(Math.Max(Size.Width, value.Width), Math.Max(Size.Height, value.Height));
847                                         }
848   
849
850                                         OnMinimumSizeChanged(EventArgs.Empty);
851                                         if (IsHandleCreated) {
852                                                 XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
853                                         }
854                                 }
855                         }
856                 }
857
858                 [Browsable(false)]
859                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
860                 public bool Modal  {
861                         get {
862                                 return is_modal;
863                         }
864                 }
865
866                 [DefaultValue(1D)]
867                 [TypeConverter(typeof(OpacityConverter))]
868                 [MWFCategory("Window Style")]
869                 public double Opacity {
870                         get {
871                                 if (IsHandleCreated) {
872                                         if ((XplatUI.SupportsTransparency () & TransparencySupport.Get) != 0)
873                                                 return XplatUI.GetWindowTransparency (Handle);
874                                 }
875
876                                 return opacity;
877                         }
878
879                         set {
880                                 opacity = value;
881
882                                 AllowTransparency = true;
883
884                                 if (IsHandleCreated) {
885                                         UpdateStyles();
886                                         if ((XplatUI.SupportsTransparency () & TransparencySupport.Set) != 0)
887                                                 XplatUI.SetWindowTransparency(Handle, opacity, TransparencyKey);
888                                 }
889                         }
890                 }
891                         
892
893                 [Browsable(false)]
894                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
895                 public Form[] OwnedForms {
896                         get {
897                                 Form[] form_list;
898
899                                 form_list = new Form[owned_forms.Count];
900
901                                 for (int i=0; i<owned_forms.Count; i++) {
902                                         form_list[i] = (Form)owned_forms[i];
903                                 }
904
905                                 return form_list;
906                         }
907                 }
908
909                 [Browsable(false)]
910                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
911                 public Form Owner {
912                         get {
913                                 return owner;
914                         }
915
916                         set {
917                                 if (owner != value) {
918                                         if (owner != null) {
919                                                 owner.RemoveOwnedForm(this);
920                                         }
921                                         owner = value;
922                                         if (owner != null)
923                                                 owner.AddOwnedForm(this);
924                                         if (IsHandleCreated) {
925                                                 if (owner != null && owner.IsHandleCreated) {
926                                                         XplatUI.SetTopmost(this.window.Handle, owner.window.Handle, true);
927                                                 } else {
928                                                         XplatUI.SetTopmost(this.window.Handle, IntPtr.Zero, false);
929                                                 }
930                                         }
931                                 }
932                         }
933                 }
934
935 #if NET_2_0
936                 [DefaultValue (true)]
937                 public bool ShowIcon {
938                         get { return this.show_icon; }
939                         set {
940                                 if (this.show_icon != value ) {
941                                         this.show_icon = value;
942                                         UpdateStyles ();
943                                         
944                                         XplatUI.SetIcon (this.Handle, value == true ? this.Icon : null);
945                                         XplatUI.InvalidateNC (this.Handle);
946                                 }
947                         }
948                 }                       
949 #endif
950         
951                 [DefaultValue(true)]
952                 [MWFCategory("Window Style")]
953                 public bool ShowInTaskbar {
954                         get {
955                                 return show_in_taskbar;
956                         }
957                         set {
958                                 if (show_in_taskbar != value) {
959                                         show_in_taskbar = value;
960                                         if (IsHandleCreated) {
961                                                 RecreateHandle();
962                                         }
963                                         UpdateStyles();
964                                 }
965                         }
966                 }
967
968                 // new property so we can set the DesignerSerializationVisibility
969                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
970                 [Localizable(false)]
971                 public new Size Size {
972                         get { return base.Size; }
973                         set { base.Size = value; }
974                 }
975
976                 [DefaultValue(SizeGripStyle.Auto)]
977                 [MWFCategory("Window Style")]
978                 public SizeGripStyle SizeGripStyle {
979                         get {
980                                 return size_grip_style;
981                         }
982
983                         set {
984                                 size_grip_style = value;
985                                 UpdateSizeGripVisible ();
986                         }
987                 }
988
989                 [DefaultValue(FormStartPosition.WindowsDefaultLocation)]
990                 [Localizable(true)]
991                 [MWFCategory("Layout")]
992                 public FormStartPosition StartPosition {
993                         get {
994                                 return start_position;
995                         }
996
997                         set {
998                                 if (start_position == FormStartPosition.WindowsDefaultLocation) {               // Only do this if it's not set yet
999                                         start_position = value;
1000                                         if (IsHandleCreated) {
1001                                                 switch(start_position) {
1002                                                         case FormStartPosition.CenterParent: {
1003                                                                 CenterToParent();
1004                                                                 break;
1005                                                         }
1006
1007                                                         case FormStartPosition.CenterScreen: {
1008                                                                 CenterToScreen();
1009                                                                 break;
1010                                                         }
1011
1012                                                         case FormStartPosition.Manual: {
1013                                                                 Left = CreateParams.X;
1014                                                                 Top = CreateParams.Y;
1015                                                                 break;
1016                                                         }
1017
1018                                                         default: {
1019                                                                 break;
1020                                                         }
1021                                                 }
1022                                         }
1023                                 }
1024                         }
1025                 }
1026
1027                 // new property so we can set EditorBrowsable to never
1028                 [Browsable(false)]
1029                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1030                 [EditorBrowsable(EditorBrowsableState.Never)]
1031                 public new int TabIndex {
1032                         get { return base.TabIndex; }
1033                         set { base.TabIndex = value; }
1034                 }
1035
1036 #if NET_2_0
1037                 [Browsable(false)]
1038                 [DefaultValue (true)]
1039                 [DispIdAttribute (-516)]
1040                 [EditorBrowsable(EditorBrowsableState.Never)]
1041                 public new bool TabStop {
1042                         get { return base.TabStop; }
1043                         set { base.TabStop = value; }
1044                 }
1045 #endif
1046
1047                 [Browsable(false)]
1048                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1049                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1050                 public bool TopLevel {
1051                         get {
1052                                 return GetTopLevel();
1053                         }
1054
1055                         set {
1056                                 if (!value && IsMdiContainer)
1057                                         throw new ArgumentException ("MDI Container forms must be top level.");
1058                                 SetTopLevel(value);
1059                         }
1060                 }
1061
1062                 [DefaultValue(false)]
1063                 [MWFCategory("Window Style")]
1064                 public bool TopMost {
1065                         get {
1066                                 return topmost;
1067                         }
1068
1069                         set {
1070                                 if (topmost != value) {
1071                                         topmost = value;
1072                                         if (IsHandleCreated)
1073                                                 XplatUI.SetTopmost(window.Handle, owner != null ? owner.window.Handle : IntPtr.Zero, value);
1074                                 }
1075                         }
1076                 }
1077
1078                 [MWFCategory("Window Style")]
1079                 public Color TransparencyKey {
1080                         get {
1081                                 return transparency_key;
1082                         }
1083
1084                         set {
1085                                 transparency_key = value;
1086
1087                                 AllowTransparency = true;
1088                                 UpdateStyles();
1089                                 if ((XplatUI.SupportsTransparency () & TransparencySupport.Set) != 0)
1090                                         XplatUI.SetWindowTransparency(Handle, Opacity, transparency_key);
1091                         }
1092                 }
1093
1094                 [DefaultValue(FormWindowState.Normal)]
1095                 [MWFCategory("Layout")]
1096                 public FormWindowState WindowState {
1097                         get {
1098                                 if (IsHandleCreated) {
1099
1100                                         if (window_manager != null)
1101                                                 return window_manager.GetWindowState ();
1102
1103                                         FormWindowState new_state = XplatUI.GetWindowState(Handle);
1104                                         if (new_state != (FormWindowState)(-1))
1105                                                 window_state = new_state;
1106                                 }
1107
1108                                 return window_state;
1109                         }
1110
1111                         set {
1112                                 FormWindowState old_state = window_state;
1113                                 window_state = value;
1114                                 if (IsHandleCreated) {
1115
1116                                         if (window_manager != null) {
1117                                                 window_manager.SetWindowState (old_state, value);
1118                                                 return;
1119                                         }
1120
1121                                         XplatUI.SetWindowState(Handle, value);
1122                                 }
1123                         }
1124                 }
1125
1126                 #endregion      // Public Instance Properties
1127
1128                 #region Protected Instance Properties
1129                 protected override CreateParams CreateParams {
1130                         get {
1131                                 CreateParams cp = new CreateParams ();
1132
1133                                 cp.Caption = Text;
1134                                 cp.ClassName = XplatUI.DefaultClassName;
1135                                 cp.ClassStyle = 0;
1136                                 cp.Style = 0;
1137                                 cp.ExStyle = 0;
1138                                 cp.Param = 0;
1139                                 cp.Parent = IntPtr.Zero;
1140                                 cp.menu = ActiveMenu;
1141                                 cp.control = this;
1142
1143                                 if (start_position == FormStartPosition.WindowsDefaultLocation && !IsMdiChild && Parent == null) {
1144                                         cp.X = unchecked ((int)0x80000000);
1145                                         cp.Y = unchecked ((int)0x80000000);
1146                                 } else {
1147                                         cp.X = Left;
1148                                         cp.Y = Top;
1149                                 }
1150                                 cp.Width = Width;
1151                                 cp.Height = Height;
1152
1153                                 cp.Style = (int)(WindowStyles.WS_CLIPCHILDREN | WindowStyles.WS_CLIPSIBLINGS);
1154
1155                                 if (Parent != null) {
1156                                         cp.Parent = Parent.Handle;
1157                                         cp.Style |= (int) WindowStyles.WS_CHILD;
1158                                 }
1159
1160                                 if (IsMdiChild) {
1161                                         cp.Style |= (int)(WindowStyles.WS_CHILD | WindowStyles.WS_CAPTION);
1162                                         if (Parent != null) {
1163                                                 cp.Parent = Parent.Handle;
1164                                         }
1165
1166                                         cp.ExStyle |= (int) (WindowExStyles.WS_EX_WINDOWEDGE | WindowExStyles.WS_EX_MDICHILD);
1167
1168                                         switch (FormBorderStyle) {
1169                                         case FormBorderStyle.None:
1170                                                 break;
1171                                         case FormBorderStyle.FixedToolWindow:
1172                                         case FormBorderStyle.SizableToolWindow:
1173                                                 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW;
1174                                                 goto default;
1175                                         default:
1176                                                 cp.Style |= (int) WindowStyles.WS_OVERLAPPEDWINDOW;
1177                                                 break;
1178                                         }
1179                                         
1180                                 } else {
1181                                         switch (FormBorderStyle) {
1182                                                 case FormBorderStyle.Fixed3D: {
1183                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1184                                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_CLIENTEDGE; 
1185                                                         break;
1186                                                 }
1187
1188                                                 case FormBorderStyle.FixedDialog: {
1189                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1190                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_DLGMODALFRAME | WindowExStyles.WS_EX_CONTROLPARENT);
1191                                                         break;
1192                                                 }
1193
1194                                                 case FormBorderStyle.FixedSingle: {
1195                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1196                                                         break;
1197                                                 }
1198
1199                                                 case FormBorderStyle.FixedToolWindow: { 
1200                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1201                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_TOOLWINDOW);
1202                                                         break;
1203                                                 }
1204
1205                                                 case FormBorderStyle.Sizable: {
1206                                                         cp.Style |= (int)(WindowStyles.WS_BORDER | WindowStyles.WS_THICKFRAME | WindowStyles.WS_CAPTION); 
1207                                                         break;
1208                                                 }
1209
1210                                                 case FormBorderStyle.SizableToolWindow: {
1211                                                         cp.Style |= (int)(WindowStyles.WS_BORDER | WindowStyles.WS_THICKFRAME | WindowStyles.WS_CAPTION);
1212                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_TOOLWINDOW);
1213                                                         break;
1214                                                 }
1215
1216                                                 case FormBorderStyle.None: {
1217                                                         break;
1218                                                 }
1219                                         }
1220                                 }
1221
1222                                 switch(window_state) {
1223                                         case FormWindowState.Maximized: {
1224                                                 cp.Style |= (int)WindowStyles.WS_MAXIMIZE;
1225                                                 break;
1226                                         }
1227
1228                                         case FormWindowState.Minimized: {
1229                                                 cp.Style |= (int)WindowStyles.WS_MINIMIZE;
1230                                                 break;
1231                                         }
1232                                 }
1233
1234                                 if (TopMost) {
1235                                         cp.ExStyle |= (int) WindowExStyles.WS_EX_TOPMOST;
1236                                 }
1237
1238                                 if (ShowInTaskbar) {
1239                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_APPWINDOW;
1240                                 }
1241
1242                                 if (MaximizeBox) {
1243                                         cp.Style |= (int)WindowStyles.WS_MAXIMIZEBOX;
1244                                 }
1245
1246                                 if (MinimizeBox) {
1247                                         cp.Style |= (int)WindowStyles.WS_MINIMIZEBOX;
1248                                 }
1249
1250                                 if (ControlBox) {
1251                                         cp.Style |= (int)WindowStyles.WS_SYSMENU;
1252                                 }
1253
1254 #if NET_2_0
1255                                 if (!this.show_icon) {
1256                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_DLGMODALFRAME;
1257                                 }
1258 #endif
1259
1260                                 if (HelpButton && !MaximizeBox && !MinimizeBox) {
1261                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_CONTEXTHELP;
1262                                 }
1263                                 
1264                                 if (VisibleInternal)
1265                                         cp.Style |= (int)WindowStyles.WS_VISIBLE;
1266
1267                                 if (opacity < 1.0 || TransparencyKey != Color.Empty) {
1268                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_LAYERED;
1269                                 }
1270
1271                                 if (!is_enabled && context == null) {
1272                                         cp.Style |= (int)(WindowStyles.WS_DISABLED);
1273                                 }
1274
1275                                 return cp;
1276                         }
1277                 }
1278
1279                 protected override ImeMode DefaultImeMode {
1280                         get {
1281                                 return ImeMode.NoControl;
1282                         }
1283                 }
1284
1285                 protected override Size DefaultSize {
1286                         get {
1287                                 return new Size (300, 300);
1288                         }
1289                 }
1290
1291                 protected Rectangle MaximizedBounds {
1292                         get {
1293                                 if (maximized_bounds != Rectangle.Empty) {
1294                                         return maximized_bounds;
1295                                 }
1296                                 return default_maximized_bounds;
1297                         }
1298
1299                         set {
1300                                 maximized_bounds = value;
1301                                 OnMaximizedBoundsChanged(EventArgs.Empty);
1302                                 if (IsHandleCreated) {
1303                                         XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
1304                                 }
1305                         }
1306                 }
1307 #if NET_2_0
1308                 [MonoTODO ("Implemented for Win32, needs X11 implementation")]
1309                 protected virtual bool ShowWithoutActivation {
1310                         get { return false; }
1311                 }
1312 #endif
1313                 #endregion      // Protected Instance Properties
1314
1315                 #region Public Static Methods
1316 #if NET_2_0
1317                 [EditorBrowsable(EditorBrowsableState.Never)]
1318                 [Obsolete ("This method has been deprecated.  Use AutoScaleDimensions instead")]
1319 #else
1320                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1321 #endif
1322                 public static SizeF GetAutoScaleSize (Font font)
1323                 {
1324                         return XplatUI.GetAutoScaleSize(font);
1325                 }
1326
1327                 #endregion      // Public Static Methods
1328
1329                 #region Public Instance Methods
1330                 internal SizeF GetAutoScaleSize (Graphics g, Font font)
1331                 {
1332                         //
1333                         // The following constants come from the dotnet mailing list
1334                         // discussion: http://discuss.develop.com/archives/wa.exe?A2=ind0203A&L=DOTNET&P=R3655
1335                         //
1336                         // The magic number is "Its almost the length
1337                         // of the string with a smattering added in
1338                         // for compat with earlier code".
1339                         //
1340         
1341                         string magic_string = "The quick brown fox jumped over the lazy dog.";
1342                         double magic_number = 44.549996948242189;
1343                         float width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
1344                         
1345                         return new SizeF (width, font.Height);
1346                 }
1347                                                  
1348                 public void Activate ()
1349                 {
1350                         Form    active;
1351
1352                         // The docs say activate only activates if our app is already active
1353                         if (IsHandleCreated) {
1354                                 if (IsMdiChild) {
1355                                         MdiParent.ActivateMdiChild (this);
1356                                 } else if (IsMdiContainer) {
1357                                         mdi_container.SendFocusToActiveChild ();
1358                                 } else {
1359                                         active = ActiveForm;
1360                                         if ((active != null) && (this != active)) {
1361                                                 XplatUI.Activate(window.Handle);
1362                                         }
1363                                 }
1364                         }
1365                 }
1366
1367                 public void AddOwnedForm(Form ownedForm) {
1368                         if (!owned_forms.Contains(ownedForm)) {
1369                                 owned_forms.Add(ownedForm);
1370                         }
1371                         ownedForm.Owner = this;
1372                 }
1373
1374                 public void Close () {
1375                         if (IsDisposed)
1376                                 return;
1377
1378                         if (!is_visible)
1379                                 return;
1380
1381                         XplatUI.SendMessage(this.Handle, Msg.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
1382                 }
1383
1384                 public void LayoutMdi(MdiLayout value) {
1385                         if (mdi_container != null) {
1386                                 mdi_container.LayoutMdi(value);
1387                         }
1388                 }
1389
1390                 public void RemoveOwnedForm(Form ownedForm) {
1391                         owned_forms.Remove(ownedForm);
1392                 }
1393
1394                 public void SetDesktopBounds(int x, int y, int width, int height) {
1395                         DesktopBounds = new Rectangle(x, y, width, height);
1396                 }
1397
1398                 public void SetDesktopLocation(int x, int y) {
1399                         DesktopLocation = new Point(x, y);
1400                 }
1401
1402 #if NET_2_0
1403                 public void Show (IWin32Window owner)
1404                 {
1405                         if (owner == null)
1406                                 this.Owner = null;
1407                         else
1408                                 this.Owner = Control.FromHandle (owner.Handle).TopLevelControl as Form;
1409
1410                         if (owner == this)
1411                                 throw new InvalidOperationException ("The 'owner' cannot be the form being shown.");
1412
1413                         base.Show ();
1414                 }
1415 #endif
1416
1417                 public DialogResult ShowDialog() {
1418                         return ShowDialog(this.owner);
1419                 }
1420
1421                 public DialogResult ShowDialog(IWin32Window ownerWin32) {
1422                         Rectangle       area;
1423                         bool            confined;
1424                         IntPtr          capture_window;
1425
1426                         owner = null;
1427
1428                         if (ownerWin32 != null) {
1429                                 Control c = Control.FromHandle (ownerWin32.Handle);
1430                                 if (c != null)
1431                                         owner = c.TopLevelControl as Form;
1432                         }
1433
1434                         if (owner == this) {
1435                                 throw new ArgumentException ("Forms cannot own themselves or their owners.", "owner");
1436                         }
1437
1438                         if (is_modal) {
1439                                 throw new InvalidOperationException ("The form is already displayed as a modal dialog.");
1440                         }
1441
1442                         if (Visible) {
1443                                 throw new InvalidOperationException ("Forms that are already "
1444                                         + " visible cannot be displayed as a modal dialog. Set the"
1445                                         + " form's visible property to false before calling"
1446                                         + " ShowDialog.");
1447                         }
1448
1449                         if (!Enabled) {
1450                                 throw new InvalidOperationException ("Forms that are not enabled"
1451                                         + " cannot be displayed as a modal dialog. Set the form's"
1452                                         + " enabled property to true before calling ShowDialog.");
1453                         }
1454
1455                         if (TopLevelControl != this) {
1456                                 throw new InvalidOperationException ("Forms that are not top level"
1457                                         + " forms cannot be displayed as a modal dialog. Remove the"
1458                                         + " form from any parent form before calling ShowDialog.");
1459                         }
1460
1461                         #if broken
1462                         // Can't do this, will screw us in the modal loop
1463                         form_parent_window.Parent = this.owner;
1464                         #endif
1465
1466                         // Release any captures
1467                         XplatUI.GrabInfo(out capture_window, out confined, out area);
1468                         if (capture_window != IntPtr.Zero) {
1469                                 XplatUI.UngrabWindow(capture_window);
1470                         }
1471
1472 #if not
1473                         // Commented out; we instead let the Visible=true inside the runloop create the control
1474                         // otherwise setting DialogResult inside any of the events that are triggered by the
1475                         // create will not actually cause the form to not be displayed.
1476                         // Leaving this comment here in case there was an actual purpose to creating the control
1477                         // in here.
1478                         if (!IsHandleCreated) {
1479                                 CreateControl();
1480                         }
1481 #endif
1482
1483                         Application.RunLoop(true, new ApplicationContext(this));
1484
1485                         if (owner != null) {
1486                                 // Cannot use Activate(), it has a check for the current active window...
1487                                 XplatUI.Activate(owner.window.Handle);
1488                         }
1489
1490                         if (DialogResult != DialogResult.None) {
1491                                 return DialogResult;
1492                         }
1493                         DialogResult = DialogResult.Cancel;
1494                         return DialogResult.Cancel;
1495                 }
1496
1497                 public override string ToString() {
1498                         return GetType().FullName.ToString() + ", Text: " + Text;
1499                 }
1500                 #endregion      // Public Instance Methods
1501
1502                 #region Protected Instance Methods
1503                 protected void ActivateMdiChild(Form form) {
1504                         if (!IsMdiContainer)
1505                                 return;
1506                         mdi_container.ActivateChild (form);
1507                         OnMdiChildActivate(EventArgs.Empty);
1508                 }
1509
1510                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1511                 protected override void AdjustFormScrollbars(bool displayScrollbars) {
1512                         base.AdjustFormScrollbars (displayScrollbars);
1513                 }
1514
1515 #if NET_2_0
1516                 [EditorBrowsable(EditorBrowsableState.Never)]
1517                 [Obsolete ("This method has been deprecated")] // XXX what to use instead?
1518 #else
1519                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1520 #endif
1521                 protected void ApplyAutoScaling()
1522                 {
1523                         SizeF current_size_f = GetAutoScaleSize (DeviceContext, Font);
1524                         Size current_size = new Size ((int) current_size_f.Width, (int) current_size_f.Height);
1525                         float   dx;
1526                         float   dy;
1527
1528                         if (current_size == autoscale_base_size)
1529                                 return;
1530
1531                         if (Environment.GetEnvironmentVariable ("MONO_MWF_SCALING") == "disable"){
1532                                 return;
1533                         }
1534                         
1535                         //
1536                         // I tried applying the Fudge height factor from:
1537                         // http://blogs.msdn.com/mharsh/archive/2004/01/25/62621.aspx
1538                         // but it makes things larger without looking better.
1539                         //
1540                         if (current_size_f.Width != AutoScaleBaseSize.Width) {
1541                                 dx = current_size_f.Width / AutoScaleBaseSize.Width + 0.08f;
1542                         } else {
1543                                 dx = 1;
1544                         }
1545
1546                         if (current_size_f.Height != AutoScaleBaseSize.Height) {
1547                                 dy = current_size_f.Height / AutoScaleBaseSize.Height + 0.08f;
1548                         } else {
1549                                 dy = 1;
1550                         }
1551
1552                         Scale (dx, dy);
1553                         
1554                         AutoScaleBaseSize = current_size;
1555                 }
1556
1557                 protected void CenterToParent() {
1558                         Control ctl;
1559                         int     w;
1560                         int     h;
1561
1562                         if (Width > 0) {
1563                                 w = Width;
1564                         } else {
1565                                 w = DefaultSize.Width;
1566                         }
1567
1568                         if (Height > 0) {
1569                                 h = Height;
1570                         } else {
1571                                 h = DefaultSize.Height;
1572                         }
1573
1574                         ctl = null;
1575                         if (Parent != null) {
1576                                 ctl = Parent;
1577                         } else if (owner != null) {
1578                                 ctl = owner;
1579                         }
1580
1581                         if (owner != null) {
1582                                 this.Location = new Point(ctl.Left + ctl.Width / 2 - w /2, ctl.Top + ctl.Height / 2 - h / 2);
1583                         }
1584                 }
1585
1586                 protected void CenterToScreen() {
1587                         Size    DisplaySize;
1588                         int     w;
1589                         int     h;
1590
1591                         if (Width > 0) {
1592                                 w = Width;
1593                         } else {
1594                                 w = DefaultSize.Width;
1595                         }
1596
1597                         if (Height > 0) {
1598                                 h = Height;
1599                         } else {
1600                                 h = DefaultSize.Height;
1601                         }
1602
1603                         XplatUI.GetDisplaySize(out DisplaySize);
1604                         this.Location = new Point(DisplaySize.Width / 2 - w / 2, DisplaySize.Height / 2 - h / 2);
1605                 }
1606
1607                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1608                 protected override Control.ControlCollection CreateControlsInstance() {
1609                         return base.CreateControlsInstance ();
1610                 }
1611
1612                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1613                 protected override void CreateHandle() {
1614                         base.CreateHandle ();
1615
1616                         if (!IsHandleCreated) {
1617                                 return;
1618                         }
1619                         
1620                         Application.AddForm (this);
1621                         
1622                         UpdateBounds();
1623
1624                         if ((XplatUI.SupportsTransparency() & TransparencySupport.Set) != 0) {
1625                                 if (allow_transparency) {
1626                                         XplatUI.SetWindowTransparency(Handle, Opacity, TransparencyKey);
1627                                 }
1628                         }
1629
1630 #if NET_2_0
1631                         if (this.ShowWithoutActivation)
1632                                 Hwnd.ObjectFromHandle (this.Handle).no_activate = true;
1633 #endif
1634
1635                         XplatUI.SetWindowMinMax(window.Handle, maximized_bounds, minimum_size, maximum_size);
1636                         if ((FormBorderStyle != FormBorderStyle.FixedDialog) && (icon != null)) {
1637                                 XplatUI.SetIcon(window.Handle, icon);
1638                         }
1639
1640                         if ((owner != null) && (owner.IsHandleCreated)) {
1641                                 XplatUI.SetTopmost(window.Handle, owner.window.Handle, true);
1642                         }
1643
1644                         for (int i = 0; i < owned_forms.Count; i++) {
1645                                 if (owned_forms[i].IsHandleCreated)
1646                                         XplatUI.SetTopmost(owned_forms[i].window.Handle, window.Handle, true);
1647                         }
1648                         
1649                         if (window_manager != null) {
1650                                 if (window_state != FormWindowState.Normal) {
1651                                         window_manager.SetWindowState (FormWindowState.Normal, window_state);
1652                                 }
1653                                 XplatUI.RequestNCRecalc (window.Handle);
1654                         }
1655
1656                 }
1657
1658                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1659                 protected override void DefWndProc(ref Message m) {
1660                         base.DefWndProc (ref m);
1661                 }
1662
1663                 protected override void Dispose(bool disposing)
1664                 {
1665                         for (int i = 0; i < owned_forms.Count; i++)
1666                                 ((Form)owned_forms[i]).Owner = null;
1667
1668                         owned_forms.Clear ();
1669                         
1670                         base.Dispose (disposing);
1671                         
1672                         Application.RemoveForm (this);
1673                 }
1674
1675                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1676                 protected virtual void OnActivated(EventArgs e)
1677                 {
1678                         EventHandler eh = (EventHandler)(Events [ActivatedEvent]);
1679                         if (eh != null)
1680                                 eh (this, e);
1681                 }
1682
1683                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1684                 protected virtual void OnClosed(EventArgs e) {
1685                         EventHandler eh = (EventHandler)(Events [ClosedEvent]);
1686                         if (eh != null)
1687                                 eh (this, e);
1688                 }
1689
1690                 // Consider calling FireClosingEvents instead of calling this directly.
1691                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1692                 protected virtual void OnClosing(System.ComponentModel.CancelEventArgs e) {
1693                         CancelEventHandler eh = (CancelEventHandler)(Events [ClosingEvent]);
1694                         if (eh != null)
1695                                 eh (this, e);
1696                 }
1697
1698                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1699                 protected override void OnCreateControl() {
1700                         base.OnCreateControl ();
1701
1702                         if (menu != null) {
1703                                 XplatUI.SetMenu(window.Handle, menu);
1704                         }
1705
1706                         OnLoad(EventArgs.Empty);
1707                         
1708                         // Send initial location
1709                         OnLocationChanged(EventArgs.Empty);
1710
1711                         if (IsMdiContainer) {
1712                                 mdi_container.LayoutMdi (MdiLayout.Cascade);
1713                         }
1714                 }
1715
1716                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1717                 protected virtual void OnDeactivate(EventArgs e) {
1718                         EventHandler eh = (EventHandler)(Events [DeactivateEvent]);
1719                         if (eh != null)
1720                                 eh (this, e);
1721                 }
1722
1723                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1724                 protected override void OnFontChanged(EventArgs e) {
1725                         base.OnFontChanged (e);
1726                 }
1727
1728                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1729                 protected override void OnHandleCreated(EventArgs e) {
1730                         XplatUI.SetBorderStyle(window.Handle, form_border_style);
1731                         base.OnHandleCreated (e);
1732                 }
1733
1734                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1735                 protected override void OnHandleDestroyed(EventArgs e) {
1736                         base.OnHandleDestroyed (e);
1737                 }
1738
1739                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1740                 protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) {
1741                         InputLanguageChangedEventHandler eh = (InputLanguageChangedEventHandler)(Events [InputLanguageChangedEvent]);
1742                         if (eh != null)
1743                                 eh (this, e);
1744                 }
1745
1746                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1747                 protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) {
1748                         InputLanguageChangingEventHandler eh = (InputLanguageChangingEventHandler)(Events [InputLanguageChangingEvent]);
1749                         if (eh != null)
1750                                 eh (this, e);
1751                 }
1752
1753                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1754                 protected virtual void OnLoad(EventArgs e) {
1755                         if (AutoScale){
1756                                 ApplyAutoScaling ();
1757                                 AutoScale = false;
1758                         }
1759
1760                         EventHandler eh = (EventHandler)(Events [LoadEvent]);
1761                         if (eh != null)
1762                                 eh (this, e);
1763
1764                         if (!IsMdiChild) {
1765                                 switch (StartPosition) {
1766                                         case FormStartPosition.CenterScreen:
1767                                                 this.CenterToScreen();
1768                                                 break;
1769                                         case FormStartPosition.CenterParent:
1770                                                 this.CenterToParent ();
1771                                                 break;
1772                                         case FormStartPosition.Manual: 
1773                                                 Left = CreateParams.X;
1774                                                 Top = CreateParams.Y;
1775                                                 break;
1776                                 }
1777                         }
1778                         is_loaded = true;
1779                 }
1780
1781                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1782                 protected virtual void OnMaximizedBoundsChanged(EventArgs e) {
1783                         EventHandler eh = (EventHandler)(Events [MaximizedBoundsChangedEvent]);
1784                         if (eh != null)
1785                                 eh (this, e);
1786                 }
1787
1788                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1789                 protected virtual void OnMaximumSizeChanged(EventArgs e) {
1790                         EventHandler eh = (EventHandler)(Events [MaximumSizeChangedEvent]);
1791                         if (eh != null)
1792                                 eh (this, e);
1793                 }
1794
1795                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1796                 protected virtual void OnMdiChildActivate(EventArgs e) {
1797                         EventHandler eh = (EventHandler)(Events [MdiChildActivateEvent]);
1798                         if (eh != null)
1799                                 eh (this, e);
1800                 }
1801
1802                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1803                 protected virtual void OnMenuComplete(EventArgs e) {
1804                         EventHandler eh = (EventHandler)(Events [MenuCompleteEvent]);
1805                         if (eh != null)
1806                                 eh (this, e);
1807                 }
1808
1809                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1810                 protected virtual void OnMenuStart(EventArgs e) {
1811                         EventHandler eh = (EventHandler)(Events [MenuStartEvent]);
1812                         if (eh != null)
1813                                 eh (this, e);
1814                 }
1815
1816                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1817                 protected virtual void OnMinimumSizeChanged(EventArgs e) {
1818                         EventHandler eh = (EventHandler)(Events [MinimumSizeChangedEvent]);
1819                         if (eh != null)
1820                                 eh (this, e);
1821                 }
1822
1823                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1824                 protected override void OnPaint (PaintEventArgs pevent) {
1825                         base.OnPaint (pevent);
1826
1827                         if (size_grip != null) {
1828                                 size_grip.HandlePaint (this, pevent);
1829                         }
1830                 }
1831
1832                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1833                 protected override void OnResize(EventArgs e) {
1834                         base.OnResize(e);
1835
1836                 }
1837
1838                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1839                 protected override void OnStyleChanged(EventArgs e) {
1840                         base.OnStyleChanged (e);
1841                 }
1842
1843                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1844                 protected override void OnTextChanged(EventArgs e) {
1845                         base.OnTextChanged (e);
1846
1847                         if (mdi_container != null)
1848                                 mdi_container.SetParentText(true);
1849                 }
1850
1851                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1852                 protected override void OnVisibleChanged(EventArgs e) {
1853                         base.OnVisibleChanged (e);
1854                         
1855                         if (Visible) {
1856                                 if (window_manager != null)
1857                                         window_manager.SetWindowState (WindowState, WindowState);
1858                         }
1859                 }
1860
1861                 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
1862                         if (base.ProcessCmdKey (ref msg, keyData)) {
1863                                 return true;
1864                         }
1865
1866                         // Give our menu a shot
1867                         if (ActiveMenu != null) {
1868                                 return ActiveMenu.ProcessCmdKey(ref msg, keyData);
1869                         }
1870
1871                         if (IsMdiChild) {
1872                                 switch (keyData)
1873                                 {
1874                                 case Keys.Control | Keys.F4:
1875                                 case Keys.Control | Keys.Shift | Keys.F4:
1876                                         Close ();
1877                                         return true;
1878                                 case Keys.Control | Keys.Tab:
1879                                 case Keys.Control | Keys.F6:
1880                                         MdiParent.MdiContainer.ActivateNextChild ();
1881                                         return true;
1882                                 case Keys.Control | Keys.Shift | Keys.Tab:
1883                                 case Keys.Control | Keys.Shift | Keys.F6:
1884                                         MdiParent.MdiContainer.ActivatePreviousChild ();
1885                                         return true;
1886                                 }
1887                         }
1888
1889                         return false;
1890                 }
1891
1892                 // LAMESPEC - Not documented that Form overrides ProcessDialogChar; class-status showed
1893                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1894                 protected override bool ProcessDialogChar(char charCode) {
1895                         return base.ProcessDialogChar (charCode);
1896                 }
1897
1898                 protected override bool ProcessDialogKey(Keys keyData) {
1899                         if ((keyData & Keys.Modifiers) == 0) {
1900                                 if (keyData == Keys.Enter) {
1901                                         IntPtr window = XplatUI.GetFocus ();
1902                                         Control c = Control.FromHandle (window);
1903                                         if (c is Button && c.FindForm () == this) {
1904                                                 ((Button)c).PerformClick ();
1905                                                 return true;
1906                                         }
1907                                         else if (accept_button != null) {
1908                                                 accept_button.PerformClick();
1909                                                 return true;
1910                                         }
1911                                 } else if (keyData == Keys.Escape && cancel_button != null) {
1912                                         cancel_button.PerformClick();
1913                                         return true;
1914                                 }
1915                         }
1916                         return base.ProcessDialogKey(keyData);
1917                 }
1918
1919                 protected override bool ProcessKeyPreview(ref Message msg) {
1920                         if (key_preview) {
1921                                 if (ProcessKeyEventArgs(ref msg)) {
1922                                         return true;
1923                                 }
1924                         }
1925                         return base.ProcessKeyPreview (ref msg);
1926                 }
1927
1928                 protected override bool ProcessTabKey(bool forward) {
1929                         return SelectNextControl(ActiveControl, forward, true, true, true);
1930                 }
1931
1932 #if NET_2_0
1933                 [EditorBrowsable(EditorBrowsableState.Never)]
1934 #else
1935                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1936 #endif
1937                 protected override void ScaleCore(float dx, float dy) {
1938                         try {
1939                                 SuspendLayout();
1940
1941                                 // We can't scale max or min windows
1942                                 if (WindowState == FormWindowState.Normal) {
1943                                         // We cannot call base since base also adjusts X/Y, but
1944                                         // a form is toplevel and doesn't move
1945                                         Size    size;
1946
1947                                         size = ClientSize;
1948                                         if (!GetStyle(ControlStyles.FixedWidth)) {
1949                                                 size.Width = (int)(size.Width * dx);
1950                                         }
1951
1952                                         if (!GetStyle(ControlStyles.FixedHeight)) {
1953                                                 size.Height = (int)(size.Height * dy);
1954                                         }
1955
1956                                         ClientSize = size;
1957                                 }
1958
1959                                 /* Now scale our children */
1960                                 Control [] controls = Controls.GetAllControls ();
1961                                 for (int i=0; i < controls.Length; i++) {
1962                                         controls[i].Scale(dx, dy);
1963                                 }
1964                         }
1965
1966                         finally {
1967                                 ResumeLayout();
1968                         }
1969                 }
1970
1971                 protected override void Select(bool directed, bool forward) {
1972                         Form    parent;
1973
1974                         if (directed) {
1975                                 base.SelectNextControl(null, forward, true, true, true);
1976                         }
1977
1978                         parent = this.ParentForm;
1979                         if (parent != null) {
1980                                 parent.ActiveControl = this;
1981                         }
1982
1983                         Activate();
1984                 }
1985
1986                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1987                 protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
1988                         base.SetBoundsCore (x, y, width, height, specified);
1989                 }
1990
1991                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1992                 protected override void SetClientSizeCore(int x, int y) {
1993                         if ((minimum_size.Width != 0) && (x < minimum_size.Width)) {
1994                                 x = minimum_size.Width;
1995                         } else if ((maximum_size.Width != 0) && (x > maximum_size.Width)) {
1996                                 x = maximum_size.Width;
1997                         }
1998
1999                         if ((minimum_size.Height != 0) && (y < minimum_size.Height)) {
2000                                 y = minimum_size.Height;
2001                         } else if ((maximum_size.Height != 0) && (y > maximum_size.Height)) {
2002                                 y = maximum_size.Height;
2003                         }
2004
2005                         Rectangle ClientRect = new Rectangle(0, 0, x, y);
2006                         Rectangle WindowRect;
2007                         CreateParams cp = this.CreateParams;
2008
2009                         clientsize_set = new Size(x, y);
2010
2011                         if (XplatUI.CalculateWindowRect(ref ClientRect, cp.Style, cp.ExStyle, cp.menu, out WindowRect)) {
2012                                 SetBounds(bounds.X, bounds.Y, WindowRect.Width, WindowRect.Height, BoundsSpecified.Size);
2013                         }
2014                 }
2015
2016                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2017                 protected override void SetVisibleCore(bool value) {
2018                         is_changing_visible_state = true;
2019                         has_been_visible = value || has_been_visible;
2020                         base.SetVisibleCore (value);
2021                         is_changing_visible_state = false;
2022                         
2023 #if NET_2_0
2024                         // Shown event is only called once, the first time the form is made visible
2025                         if (value && !shown_raised) {
2026                                 this.OnShown (EventArgs.Empty);
2027                                 shown_raised = true;
2028                         }
2029 #endif
2030                 }
2031
2032                 protected override void UpdateDefaultButton() {
2033                         base.UpdateDefaultButton ();
2034                 }
2035
2036                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2037                 protected override void WndProc(ref Message m) {
2038 #if debug
2039                         Console.WriteLine(DateTime.Now.ToLongTimeString () + " Form {0} ({2}) received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), m.ToString (), Text);
2040 #endif
2041
2042                         if (window_manager != null && window_manager.WndProc (ref m)) {
2043                                 return;
2044                         }
2045
2046                         switch((Msg)m.Msg) {
2047                                 case Msg.WM_DESTROY: {
2048                                         base.WndProc(ref m);
2049                                         if (!RecreatingHandle) {
2050                                                 this.closing = true;
2051                                         }
2052                                         return;
2053                                 }
2054
2055                                 case Msg.WM_CLOSE_INTERNAL: {
2056                                         DestroyHandle();
2057                                         break;
2058                                 }
2059
2060                                 case Msg.WM_CLOSE: {
2061                                         Form act = Form.ActiveForm;
2062                                         // Don't close this form if there's another modal form visible.
2063                                         if (act != null && act != this && act.Modal == true) {
2064                                                 // Check if any of the parents up the tree is the modal form, 
2065                                                 // in which case we can still close this form.
2066                                                 Control current = this;
2067                                                 while (current != null && current.Parent != act) {
2068                                                         current = current.Parent;
2069                                                 }
2070                                                 if (current == null || current.Parent != act) {
2071                                                         return;
2072                                                 }
2073                                         }
2074
2075                                         if (mdi_container != null) {
2076                                                 foreach (Form mdi_child in mdi_container.MdiChildren) {
2077                                                         mdi_child.FireClosingEvents (CloseReason.MdiFormClosing);
2078                                                 }
2079                                         }
2080
2081                                         if (!is_modal) {
2082                                                 if (!FireClosingEvents (CloseReason.UserClosing)) {
2083                                                         OnClosed (EventArgs.Empty);
2084 #if NET_2_0
2085                                                         OnFormClosed (new FormClosedEventArgs (CloseReason.UserClosing));
2086 #endif
2087                                                         closing = true;
2088                                                         Dispose ();
2089                                                 }
2090                                                 else {
2091                                                         closing = false;
2092                                                 }
2093                                         } else {
2094                                                 if (FireClosingEvents (CloseReason.UserClosing)) {
2095                                                         DialogResult = DialogResult.None;
2096                                                         closing = false;
2097                                                 }
2098                                                 else {
2099                                                         OnClosed (EventArgs.Empty);
2100 #if NET_2_0
2101                                                         OnFormClosed (new FormClosedEventArgs (CloseReason.UserClosing));
2102 #endif
2103                                                         closing = true;
2104                                                         Hide ();
2105                                                 }
2106                                         }
2107
2108                                         return;
2109                                 }
2110
2111                                 case Msg.WM_WINDOWPOSCHANGED: {
2112                                         if (WindowState != FormWindowState.Minimized) {
2113                                                 base.WndProc(ref m);
2114                                         }
2115                                         return;
2116                                 }
2117
2118 #if NET_2_0
2119                                 case Msg.WM_SYSCOMMAND: {
2120                                         // Let *Strips know the app's title bar was clicked
2121                                         if (XplatUI.IsEnabled (Handle))
2122                                                 ToolStripManager.FireAppClicked ();
2123                                                 
2124                                         base.WndProc(ref m);
2125                                         break;
2126                                 }
2127 #endif
2128         
2129                                 case Msg.WM_ACTIVATE: {
2130                                         if (m.WParam != (IntPtr)WindowActiveFlags.WA_INACTIVE) {
2131                                                 if (is_loaded) {
2132                                                         SelectActiveControl ();
2133
2134                                                         if (ActiveControl != null && !ActiveControl.Focused)
2135                                                                 SendControlFocus (ActiveControl);
2136                                                 }
2137
2138                                                 OnActivated(EventArgs.Empty);
2139                                         } else {
2140                                                 OnDeactivate(EventArgs.Empty);
2141                                         }
2142                                         return;
2143                                 }
2144
2145                                 case Msg.WM_KILLFOCUS: {
2146                                         base.WndProc(ref m);
2147                                         return;
2148                                 }
2149
2150                                 case Msg.WM_SETFOCUS: {
2151                                         if (ActiveControl != null && ActiveControl != this) {
2152                                                 ActiveControl.Focus();
2153                                                 return; // FIXME - do we need to run base.WndProc, even though we just changed focus?
2154                                         }
2155                                         if (IsMdiContainer) {
2156                                                 mdi_container.SendFocusToActiveChild ();
2157                                                 return;
2158                                         }
2159                                         base.WndProc(ref m);
2160                                         return;
2161                                 }
2162
2163                                 // Menu drawing
2164                 case Msg.WM_NCHITTEST: {
2165                                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2166                                                 int x = LowOrder ((int)m.LParam.ToInt32 ());
2167                                                 int y = HighOrder ((int)m.LParam.ToInt32 ());
2168
2169                                                 XplatUI.ScreenToMenu (ActiveMenu.Wnd.window.Handle, ref x, ref y);
2170
2171                                                 // If point is under menu return HTMENU, it prevents Win32 to return HTMOVE.
2172                                                 if ((x > 0) && (y > 0) && (x < ActiveMenu.Rect.Width) && (y < ActiveMenu.Rect.Height)) {
2173                                                         m.Result = new IntPtr ((int)HitTest.HTMENU);
2174                                                         return;
2175                                                 }
2176                                         }
2177
2178                                         base.WndProc (ref m);
2179                                         return;
2180                                 }
2181
2182                 case Msg.WM_NCLBUTTONDOWN: {
2183                                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2184                                                 ActiveMenu.OnMouseDown(this, new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), mouse_clicks, Control.MousePosition.X, Control.MousePosition.Y, 0));
2185                                         }
2186
2187                                         if (ActiveMaximizedMdiChild != null) {
2188                                                 if (ActiveMaximizedMdiChild.HandleMenuMouseDown (ActiveMenu,
2189                                                                 LowOrder ((int) m.LParam.ToInt32 ()),
2190                                                                 HighOrder ((int) m.LParam.ToInt32 ()))) {
2191                                                         // Don't let base process this message, otherwise we won't
2192                                                         // get a WM_NCLBUTTONUP.
2193                                                         return;
2194                                                 }
2195                                         }
2196                                         base.WndProc(ref m);
2197                                         return;
2198                                 }
2199
2200                 case Msg.WM_NCLBUTTONUP: {
2201                                         if (ActiveMaximizedMdiChild != null) {
2202                                                 ActiveMaximizedMdiChild.HandleMenuMouseUp (ActiveMenu,
2203                                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2204                                                                 HighOrder ((int)m.LParam.ToInt32 ()));
2205                                         }
2206                                         base.WndProc (ref m);
2207                                         return;
2208                                 }
2209
2210                                 case Msg.WM_NCMOUSELEAVE: {
2211                                         if (ActiveMaximizedMdiChild != null) {
2212                                                 ActiveMaximizedMdiChild.HandleMenuMouseLeave(ActiveMenu,
2213                                                                 LowOrder((int)m.LParam.ToInt32()),
2214                                                                 HighOrder((int)m.LParam.ToInt32()));
2215                                         }
2216                                         base.WndProc(ref m);
2217                                         return;
2218                                 }
2219                                 
2220                                 case Msg.WM_NCMOUSEMOVE: {
2221                                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2222                                                 ActiveMenu.OnMouseMove(this, new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 0));
2223                                         }
2224                                         
2225                                         if (ActiveMaximizedMdiChild != null) {
2226                                                 XplatUI.RequestAdditionalWM_NCMessages (Handle, false, true);
2227                                                 ActiveMaximizedMdiChild.HandleMenuMouseMove (ActiveMenu,
2228                                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2229                                                                 HighOrder ((int)m.LParam.ToInt32 ()));
2230                                         }
2231                                         base.WndProc(ref m);
2232                                         return;
2233                                 }
2234
2235                                 case Msg.WM_NCPAINT: {
2236                                         if (ActiveMenu != null) {
2237                                                 PaintEventArgs  pe;
2238                                                 Point           pnt;
2239
2240                                                 pe = XplatUI.PaintEventStart(Handle, false);
2241                                                 pnt = XplatUI.GetMenuOrigin(window.Handle);
2242
2243                                                 // The entire menu has to be in the clip rectangle because the 
2244                                                 // control buttons are right-aligned and otherwise they would
2245                                                 // stay painted when the window gets resized.
2246                                                 Rectangle clip = new Rectangle (pnt.X, pnt.Y, ClientSize.Width, 0);
2247                                                 clip = Rectangle.Union(clip, pe.ClipRectangle);
2248                                                 pe.SetClip(clip);
2249                                                 pe.Graphics.SetClip(clip);
2250                                                 
2251                                                 ActiveMenu.Draw (pe, new Rectangle (pnt.X, pnt.Y, ClientSize.Width, 0));
2252
2253                                                 if (ActiveMaximizedMdiChild != null) {
2254                                                         ActiveMaximizedMdiChild.DrawMaximizedButtons (ActiveMenu, pe);
2255                                                 }
2256
2257                                                 XplatUI.PaintEventEnd(Handle, false);
2258                                         }
2259
2260                                         base.WndProc(ref m);
2261                                         return;
2262                                 }
2263
2264                                 case Msg.WM_NCCALCSIZE: {
2265                                         XplatUIWin32.NCCALCSIZE_PARAMS  ncp;
2266
2267                                         if ((ActiveMenu != null) && (m.WParam == (IntPtr)1)) {
2268                                                 ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure(m.LParam, typeof(XplatUIWin32.NCCALCSIZE_PARAMS));
2269
2270                                                 // Adjust for menu
2271                                                 ncp.rgrc1.top += ThemeEngine.Current.CalcMenuBarSize (DeviceContext, ActiveMenu, ClientSize.Width);
2272                                                 Marshal.StructureToPtr(ncp, m.LParam, true);
2273                                         }
2274                                         DefWndProc(ref m);
2275                                         break;
2276                                 }
2277
2278                                 case Msg.WM_MOUSEMOVE: {
2279                                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
2280                                                 MouseEventArgs args;
2281
2282                                                 args = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
2283                                                         mouse_clicks,  LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()),  0);
2284                                                 active_tracker.OnMotion(new MouseEventArgs (args.Button, args.Clicks, Control.MousePosition.X, Control.MousePosition.Y, args.Delta));
2285                                                 break;
2286                                         }
2287                                         base.WndProc(ref m);
2288                                         break;
2289                                 }
2290
2291                                 case Msg.WM_LBUTTONDOWN:
2292                                 case Msg.WM_MBUTTONDOWN:
2293                                 case Msg.WM_RBUTTONDOWN: {                                      
2294                                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
2295                                                 MouseEventArgs args;
2296
2297                                                 args = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
2298                                                         mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 0);
2299                                                 active_tracker.OnMouseDown(new MouseEventArgs (args.Button, args.Clicks, Control.MousePosition.X, Control.MousePosition.Y, args.Delta));
2300                                                 return;
2301                                         }
2302 #if NET_2_0
2303                                         ToolStripManager.FireAppClicked ();
2304 #endif
2305                                         base.WndProc (ref m);
2306                                         return;
2307                                 }
2308
2309                                 case Msg.WM_LBUTTONUP:
2310                                 case Msg.WM_MBUTTONUP:
2311                                 case Msg.WM_RBUTTONUP: {
2312                                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
2313                                                 MouseEventArgs args;
2314                                                 MouseButtons mb = FromParamToMouseButtons ((int) m.WParam.ToInt32());
2315                                                 
2316                                                 // We add in the button that was released (not sent in WParam)
2317                                                 switch((Msg)m.Msg) {
2318                                                         case Msg.WM_LBUTTONUP:
2319                                                                 mb |= MouseButtons.Left;
2320                                                                 break;
2321                                                         case Msg.WM_MBUTTONUP:
2322                                                                 mb |= MouseButtons.Middle;
2323                                                                 break;
2324                                                         case Msg.WM_RBUTTONUP:
2325                                                                 mb |= MouseButtons.Right;
2326                                                                 break;
2327                                                 }
2328                                                 
2329                                                 args = new MouseEventArgs (mb, mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 0);
2330                                                 active_tracker.OnMouseUp(new MouseEventArgs (args.Button, args.Clicks, Control.MousePosition.X, Control.MousePosition.Y, args.Delta));
2331                                                 mouse_clicks = 1;
2332                                                 return;
2333                                         }
2334                                         base.WndProc(ref m);
2335                                         return;
2336                                 }
2337
2338                                 case Msg.WM_GETMINMAXINFO: {
2339                                         MINMAXINFO      mmi;
2340
2341                                         if (m.LParam != IntPtr.Zero) {
2342                                                 mmi = (MINMAXINFO)Marshal.PtrToStructure(m.LParam, typeof(MINMAXINFO));
2343
2344                                                 default_maximized_bounds = new Rectangle(mmi.ptMaxPosition.x, mmi.ptMaxPosition.y, mmi.ptMaxSize.x, mmi.ptMaxSize.y);
2345                                                 if (maximized_bounds != Rectangle.Empty) {
2346                                                         mmi.ptMaxPosition.x = maximized_bounds.Left;
2347                                                         mmi.ptMaxPosition.y = maximized_bounds.Top;
2348                                                         mmi.ptMaxSize.x = maximized_bounds.Width;
2349                                                         mmi.ptMaxSize.y = maximized_bounds.Height;
2350                                                 }
2351
2352                                                 if (minimum_size != Size.Empty) {
2353                                                         mmi.ptMinTrackSize.x = minimum_size.Width;
2354                                                         mmi.ptMinTrackSize.y = minimum_size.Height;
2355                                                 }
2356
2357                                                 if (maximum_size != Size.Empty) {
2358                                                         mmi.ptMaxTrackSize.x = maximum_size.Width;
2359                                                         mmi.ptMaxTrackSize.y = maximum_size.Height;
2360                                                 }
2361                                                 Marshal.StructureToPtr(mmi, m.LParam, false);
2362                                         }
2363                                         break;
2364                                 }
2365                                 
2366 #if NET_2_0
2367                                 case Msg.WM_MOUSEACTIVATE: {
2368                                         // Let *Strips know the form or another control has been clicked
2369                                         if (XplatUI.IsEnabled (Handle))
2370                                                 ToolStripManager.FireAppClicked ();
2371                                                 
2372                                         base.WndProc (ref m);
2373                                         break;                          
2374                                 }
2375                                 
2376                                 case Msg.WM_ACTIVATEAPP: {
2377                                         // Let *Strips know the app lost focus
2378                                         if (m.WParam == (IntPtr)0) 
2379                                                 if (XplatUI.IsEnabled (Handle))
2380                                                         ToolStripManager.FireAppFocusChanged (this);
2381                                                         
2382                                         base.WndProc (ref m);
2383                                         break;                          
2384                                 }
2385 #endif
2386
2387                                 default: {
2388                                         base.WndProc (ref m);
2389                                         break;
2390                                 }
2391                         }
2392                 }
2393                 #endregion      // Protected Instance Methods
2394
2395                 internal override void FireEnter ()
2396                 {
2397                         // do nothing - forms don't generate OnEnter
2398                 }
2399
2400                 internal override void FireLeave ()
2401                 {
2402                         // do nothing - forms don't generate OnLeave
2403                 }
2404
2405                 internal void RemoveWindowManager ()
2406                 {
2407                         window_manager = null;
2408                 }
2409                 
2410                 internal override void CheckAcceptButton()
2411                 {
2412                         if (accept_button != null) {
2413                                 Button a_button = accept_button as Button;
2414                                 
2415                                 if (ActiveControl == a_button)
2416                                         return;
2417                                 
2418                                 if (ActiveControl is Button) {
2419                                         a_button.paint_as_acceptbutton = false;
2420                                         a_button.Redraw();
2421                                         return;
2422                                 } else {
2423                                         a_button.paint_as_acceptbutton = true;
2424                                         a_button.Redraw();
2425                                 }
2426                         }
2427                 }
2428                 
2429                 #region Events
2430                 static object ActivatedEvent = new object ();
2431                 static object ClosedEvent = new object ();
2432                 static object ClosingEvent = new object ();
2433                 static object DeactivateEvent = new object ();
2434                 static object InputLanguageChangedEvent = new object ();
2435                 static object InputLanguageChangingEvent = new object ();
2436                 static object LoadEvent = new object ();
2437                 static object MaximizedBoundsChangedEvent = new object ();
2438                 static object MaximumSizeChangedEvent = new object ();
2439                 static object MdiChildActivateEvent = new object ();
2440                 static object MenuCompleteEvent = new object ();
2441                 static object MenuStartEvent = new object ();
2442                 static object MinimumSizeChangedEvent = new object ();
2443
2444                 public event EventHandler Activated {
2445                         add { Events.AddHandler (ActivatedEvent, value); }
2446                         remove { Events.RemoveHandler (ActivatedEvent, value); }
2447                 }
2448
2449 #if NET_2_0
2450                 [Browsable (false)]
2451                 [EditorBrowsable (EditorBrowsableState.Never)]
2452 #endif
2453                 public event EventHandler Closed {
2454                         add { Events.AddHandler (ClosedEvent, value); }
2455                         remove { Events.RemoveHandler (ClosedEvent, value); }
2456                 }
2457
2458 #if NET_2_0
2459                 [Browsable (false)]
2460                 [EditorBrowsable (EditorBrowsableState.Never)]
2461 #endif
2462                 public event CancelEventHandler Closing {
2463                         add { Events.AddHandler (ClosingEvent, value); }
2464                         remove { Events.RemoveHandler (ClosingEvent, value); }
2465                 }
2466
2467                 public event EventHandler Deactivate {
2468                         add { Events.AddHandler (DeactivateEvent, value); }
2469                         remove { Events.RemoveHandler (DeactivateEvent, value); }
2470                 }
2471
2472                 public event InputLanguageChangedEventHandler InputLanguageChanged {
2473                         add { Events.AddHandler (InputLanguageChangedEvent, value); }
2474                         remove { Events.RemoveHandler (InputLanguageChangedEvent, value); }
2475                 }
2476
2477                 public event InputLanguageChangingEventHandler InputLanguageChanging {
2478                         add { Events.AddHandler (InputLanguageChangingEvent, value); }
2479                         remove { Events.RemoveHandler (InputLanguageChangingEvent, value); }
2480                 }
2481
2482                 public event EventHandler Load {
2483                         add { Events.AddHandler (LoadEvent, value); }
2484                         remove { Events.RemoveHandler (LoadEvent, value); }
2485                 }
2486
2487                 public event EventHandler MaximizedBoundsChanged {
2488                         add { Events.AddHandler (MaximizedBoundsChangedEvent, value); }
2489                         remove { Events.RemoveHandler (MaximizedBoundsChangedEvent, value); }
2490                 }
2491
2492                 public event EventHandler MaximumSizeChanged {
2493                         add { Events.AddHandler (MaximumSizeChangedEvent, value); }
2494                         remove { Events.RemoveHandler (MaximumSizeChangedEvent, value); }
2495                 }
2496
2497                 public event EventHandler MdiChildActivate {
2498                         add { Events.AddHandler (MdiChildActivateEvent, value); }
2499                         remove { Events.RemoveHandler (MdiChildActivateEvent, value); }
2500                 }
2501
2502 #if NET_2_0
2503                 [Browsable (false)]
2504 #endif
2505                 public event EventHandler MenuComplete {
2506                         add { Events.AddHandler (MenuCompleteEvent, value); }
2507                         remove { Events.RemoveHandler (MenuCompleteEvent, value); }
2508                 }
2509
2510 #if NET_2_0
2511                 [Browsable (false)]
2512 #endif
2513                 public event EventHandler MenuStart {
2514                         add { Events.AddHandler (MenuStartEvent, value); }
2515                         remove { Events.RemoveHandler (MenuStartEvent, value); }
2516                 }
2517
2518                 public event EventHandler MinimumSizeChanged {
2519                         add { Events.AddHandler (MinimumSizeChangedEvent, value); }
2520                         remove { Events.RemoveHandler (MinimumSizeChangedEvent, value); }
2521                 }
2522
2523
2524                 [Browsable(false)]
2525                 [EditorBrowsable(EditorBrowsableState.Never)]
2526                 public new event EventHandler TabIndexChanged {
2527                         add { base.TabIndexChanged += value; }
2528                         remove { base.TabIndexChanged -= value; }
2529                 }
2530                 #endregion      // Events
2531
2532 #if NET_2_0
2533                 [SettingsBindable (true)]
2534                 public override string Text {
2535                         get {
2536                                 return base.Text;
2537                         }
2538
2539                         set {
2540                                 base.Text = value;
2541                         }
2542                 }
2543
2544                 [SettingsBindable (true)]
2545                 public new Point Location {
2546                         get {
2547                                 return base.Location;
2548                         }
2549
2550                         set {
2551                                 base.Location = value;
2552                         }
2553                 }
2554
2555                 static object FormClosingEvent = new object ();
2556                 static object FormClosedEvent = new object ();
2557                 static object HelpButtonClickedEvent = new object ();
2558                 static object ResizeEndEvent = new object ();
2559                 static object ResizeBeginEvent = new object ();
2560                 static object RightToLeftLayoutChangedEvent = new object ();
2561                 static object ShownEvent = new object ();
2562
2563                 [Browsable (true)]
2564                 [EditorBrowsable (EditorBrowsableState.Always)]
2565                 public new event EventHandler AutoSizeChanged {
2566                         add { base.AutoSizeChanged += value; }
2567                         remove { base.AutoSizeChanged -= value; }
2568                 }
2569
2570                 [Browsable (true)]
2571                 [EditorBrowsable (EditorBrowsableState.Always)]
2572                 public new event EventHandler AutoValidateChanged {
2573                         add { base.AutoValidateChanged += value; }
2574                         remove { base.AutoValidateChanged -= value; }
2575                 }
2576
2577                 public event FormClosingEventHandler FormClosing {
2578                         add { Events.AddHandler (FormClosingEvent, value); }
2579                         remove { Events.RemoveHandler (FormClosingEvent, value); }
2580                 }
2581
2582                 public event FormClosedEventHandler FormClosed {
2583                         add { Events.AddHandler (FormClosedEvent, value); }
2584                         remove { Events.RemoveHandler (FormClosedEvent, value); }
2585                 }
2586
2587                 [Browsable (true)]
2588                 [EditorBrowsable (EditorBrowsableState.Always)]
2589                 public event CancelEventHandler HelpButtonClicked {
2590                         add { Events.AddHandler (HelpButtonClickedEvent, value); }
2591                         remove { Events.RemoveHandler (HelpButtonClickedEvent, value); }
2592                 }
2593
2594                 [Browsable (false)]
2595                 [EditorBrowsable (EditorBrowsableState.Never)]
2596                 public new event EventHandler MarginChanged {
2597                         add { base.MarginChanged += value; }
2598                         remove { base.MarginChanged -= value; }
2599                 }
2600
2601                 public event EventHandler RightToLeftLayoutChanged {
2602                         add { Events.AddHandler (RightToLeftLayoutChangedEvent, value); }
2603                         remove { Events.RemoveHandler (RightToLeftLayoutChangedEvent, value); }
2604                 }
2605
2606                 public event EventHandler ResizeBegin {
2607                         add { Events.AddHandler (ResizeBeginEvent, value); }
2608                         remove { Events.RemoveHandler (ResizeBeginEvent, value); }
2609                 }
2610
2611                 public event EventHandler ResizeEnd {
2612                         add { Events.AddHandler (ResizeEndEvent, value); }
2613                         remove { Events.RemoveHandler (ResizeEndEvent, value); }
2614                 }
2615
2616                 public event EventHandler Shown {
2617                         add { Events.AddHandler (ShownEvent, value); }
2618                         remove { Events.RemoveHandler (ShownEvent, value); }
2619                 }
2620
2621                 [Browsable (false)]
2622                 [EditorBrowsable (EditorBrowsableState.Never)]
2623                 public new event EventHandler TabStopChanged {
2624                         add { base.TabStopChanged += value; }
2625                         remove { base.TabStopChanged -= value; }
2626                 }
2627
2628                 protected override void OnBackgroundImageChanged (EventArgs e)
2629                 {
2630                         base.OnBackgroundImageChanged (e);
2631                 }
2632
2633                 protected override void OnBackgroundImageLayoutChanged (EventArgs e)
2634                 {
2635                         base.OnBackgroundImageLayoutChanged (e);
2636                 }
2637
2638                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2639                 protected override void OnEnabledChanged (EventArgs e)
2640                 {
2641                         base.OnEnabledChanged (e);
2642                 }
2643
2644                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2645                 protected override void OnEnter (EventArgs e)
2646                 {
2647                         base.OnEnter (e);
2648                 }
2649
2650                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2651                 protected virtual void OnFormClosed (FormClosedEventArgs e) {
2652                         FormClosedEventHandler eh = (FormClosedEventHandler)(Events[FormClosedEvent]);
2653                         if (eh != null)
2654                                 eh (this, e);
2655                 }
2656                 
2657                 // Consider calling FireClosingEvents instead of calling this directly.
2658                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2659                 protected virtual void OnFormClosing (FormClosingEventArgs e)
2660                 {
2661                         FormClosingEventHandler eh = (FormClosingEventHandler)(Events [FormClosingEvent]);
2662                         if (eh != null)
2663                                 eh (this, e);
2664                 }
2665
2666                 [MonoTODO ("Not hooked up to event")]
2667                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2668                 protected virtual void OnHelpButtonClicked (CancelEventArgs e)
2669                 {
2670                         CancelEventHandler eh = (CancelEventHandler)(Events[HelpButtonClickedEvent]);
2671                         if (eh != null)
2672                                 eh (this, e);
2673                 }
2674
2675                 protected override void OnLayout (LayoutEventArgs levent)
2676                 {
2677                         base.OnLayout (levent);
2678                 }
2679
2680                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2681                 protected virtual void OnResizeBegin (EventArgs e)
2682                 {
2683                         EventHandler eh = (EventHandler) (Events [ResizeBeginEvent]);
2684                         if (eh != null)
2685                                 eh (this, e);
2686                 }
2687
2688                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2689                 protected virtual void OnResizeEnd (EventArgs e)
2690                 {
2691                         EventHandler eh = (EventHandler) (Events [ResizeEndEvent]);
2692                         if (eh != null)
2693                                 eh (this, e);
2694                 }
2695
2696                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2697                 protected virtual void OnShown (EventArgs e)
2698                 {
2699                         EventHandler eh = (EventHandler) (Events [ShownEvent]);
2700                         if (eh != null)
2701                                 eh (this, e);
2702                 }
2703 #endif
2704         }
2705 }