Merge pull request #1275 from ranma42/fix-lib64
[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 using System.Collections.Generic;
37
38 namespace System.Windows.Forms {
39         [DesignerCategory("Form")]
40         [DesignTimeVisible(false)]
41         [Designer("System.Windows.Forms.Design.FormDocumentDesigner, " + Consts.AssemblySystem_Design, typeof(IRootDesigner))]
42         [DefaultEvent("Load")]
43         [ClassInterface (ClassInterfaceType.AutoDispatch)]
44         [InitializationEvent ("Load")]
45         [ComVisible (true)]
46         [ToolboxItemFilter ("System.Windows.Forms.Control.TopLevel")]
47         [ToolboxItem(false)]
48         public class Form : ContainerControl {
49                 #region Local Variables
50                 internal bool                   closing;
51                 private bool                    closed;
52                 FormBorderStyle                 form_border_style;
53                 private bool                    is_active;
54                 private bool                    autoscale;
55                 private Size                    clientsize_set;
56                 private Size                    autoscale_base_size;
57                 private bool                    allow_transparency;
58                 private static Icon             default_icon;
59                 internal bool                   is_modal;
60                 internal FormWindowState        window_state;
61                 private bool                    control_box;
62                 private bool                    minimize_box;
63                 private bool                    maximize_box;
64                 private bool                    help_button;
65                 private bool                    show_in_taskbar;
66                 private bool                    topmost;
67                 private IButtonControl          accept_button;
68                 private IButtonControl          cancel_button;
69                 private DialogResult            dialog_result;
70                 private FormStartPosition       start_position;
71                 private Form                    owner;
72                 private Form.ControlCollection  owned_forms;
73                 private MdiClient               mdi_container;
74                 internal InternalWindowManager  window_manager;
75                 private Form                    mdi_parent;
76                 private bool                    key_preview;
77                 private MainMenu                menu;
78                 private Icon                    icon;
79                 private Size                    maximum_size;
80                 private Size                    minimum_size;
81                 private SizeGripStyle           size_grip_style;
82                 private SizeGrip                size_grip;
83                 private Rectangle               maximized_bounds;
84                 private Rectangle               default_maximized_bounds;
85                 private double                  opacity;
86                 internal ApplicationContext     context;
87                 Color                           transparency_key;
88                 private bool                    is_loaded;
89                 internal int                    is_changing_visible_state;
90                 internal bool                   has_been_visible;
91                 private bool                    shown_raised;
92                 private bool                    close_raised;
93                 private bool                    is_clientsize_set;
94                 internal bool                   suppress_closing_events;
95                 internal bool                   waiting_showwindow; // for XplatUIX11
96                 private bool                    is_minimizing;
97                 private bool                    show_icon = true;
98                 private MenuStrip               main_menu_strip;
99                 private bool                    right_to_left_layout;
100                 private Rectangle               restore_bounds;
101                 private bool                    autoscale_base_size_set;
102                 internal ArrayList disabled_by_showdialog = new ArrayList();
103                 internal static ArrayList modal_dialogs = new ArrayList();
104                 #endregion      // Local Variables
105
106                 #region Private & Internal Methods
107                 static Form ()
108                 {
109                         default_icon = ResourceImageLoader.GetIcon ("mono.ico");
110                 }
111
112                 internal bool IsLoaded {
113                         get { return is_loaded; }
114                 }
115
116                 internal bool IsActive {
117                         get {
118                                 return is_active;
119                         }
120                         set {
121                                 if (is_active == value || IsRecreating) {
122                                         return;
123                                 }
124                                 
125                                 is_active = value;
126                                 if (is_active) {
127                                         Application.AddForm (this);
128                                         OnActivated (EventArgs.Empty);
129                                 } else {
130                                         OnDeactivate (EventArgs.Empty);
131                                 }
132                         }
133                 }
134
135                 // warning: this is only hooked up when an mdi container is created.
136                 private void ControlAddedHandler (object sender, ControlEventArgs e)
137                 {
138                         if (mdi_container != null) {
139                                 mdi_container.SendToBack ();
140                         }
141                 }
142
143                 // Convenience method for fire BOTH OnClosing and OnFormClosing events
144                 // Returns the value of Cancel, so true means the Close was cancelled,
145                 // and you shouldn't close the form.
146                 internal bool FireClosingEvents (CloseReason reason, bool cancel)
147                 {
148                         CancelEventArgs cea = new CancelEventArgs (cancel);
149                         this.OnClosing (cea);
150                         
151                         FormClosingEventArgs fcea = new FormClosingEventArgs (reason, cea.Cancel);
152                         this.OnFormClosing (fcea);
153                         return fcea.Cancel;
154                 }
155
156                 // Convenience method for fire BOTH OnClosed and OnFormClosed events
157                 private void FireClosedEvents (CloseReason reason)
158                 {
159                         this.OnClosed (EventArgs.Empty);
160                         this.OnFormClosed (new FormClosedEventArgs (reason));
161                 }
162                 
163                 internal override Size GetPreferredSizeCore (Size proposedSize)
164                 {
165                         Size retsize = Size.Empty;
166                         
167                         foreach (Control child in Controls) {
168                                 Size child_preferred_size;
169                                 if (child.AutoSize)
170                                         child_preferred_size = child.PreferredSize;
171                                 else
172                                         child_preferred_size = child.ExplicitBounds.Size;
173                                 int child_right = child.Bounds.X + child_preferred_size.Width;
174                                 int child_bottom = child.Bounds.Y + child_preferred_size.Height;
175
176                                 if (child.Dock == DockStyle.Fill) {
177                                         if (child_right > retsize.Width)
178                                                 retsize.Width = child_right;
179                                 } 
180                                 else if (child.Dock != DockStyle.Top && child.Dock != DockStyle.Bottom && child_right > retsize.Width)
181                                         retsize.Width = child_right + child.Margin.Right;
182
183                                 if (child.Dock == DockStyle.Fill) {
184                                         if (child_bottom > retsize.Height)
185                                                 retsize.Height = child_bottom;
186                                 }
187                                 else if (child.Dock != DockStyle.Left && child.Dock != DockStyle.Right && child_bottom > retsize.Height)
188                                         retsize.Height = child_bottom + child.Margin.Bottom;
189                         }
190
191                         if (retsize == Size.Empty) { // no child controls
192                                 retsize.Height += this.Padding.Top;
193                                 retsize.Width += this.Padding.Left;
194                         }
195                         retsize.Height += this.Padding.Bottom;
196                         retsize.Width += this.Padding.Right;
197
198                         return SizeFromClientSize (retsize);
199                 }
200
201                 [EditorBrowsable (EditorBrowsableState.Advanced)]
202                 protected override Rectangle GetScaledBounds (Rectangle bounds, SizeF factor, BoundsSpecified specified)
203                 {
204                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width) {
205                                 int border = Size.Width - ClientSize.Width;
206                                 bounds.Width = (int)Math.Round ((bounds.Width - border) * factor.Width) + border;
207                         }
208                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height) {
209                                 int border = Size.Height - ClientSize.Height;
210                                 bounds.Height = (int)Math.Round ((bounds.Height - border) * factor.Height) + border;
211                         }
212
213                         return bounds;
214                 }
215
216                 protected override bool ProcessMnemonic (char charCode)
217                 {
218                         return base.ProcessMnemonic (charCode);
219                 }
220                 
221                 [EditorBrowsable (EditorBrowsableState.Advanced)]
222                 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
223                 {
224                         base.ScaleControl (factor, specified);
225                 }
226
227                 internal void OnActivatedInternal ()
228                 {
229                         OnActivated (EventArgs.Empty);
230                 }
231                 
232                 internal void OnDeactivateInternal ()
233                 {
234                         OnDeactivate (EventArgs.Empty);
235                 }
236
237                 internal override void UpdateWindowText ()
238                 {
239                         if (!IsHandleCreated) {
240                                 return;
241                         }
242                         
243                         if (shown_raised) {
244                                 /* we need to call .SetWindowStyle here instead of just .Text
245                                    because the presence/absence of Text (== "" or not) can cause
246                                    other window style things to appear/disappear */
247                                 XplatUI.SetWindowStyle (window.Handle, CreateParams);
248                         }
249                         
250                         XplatUI.Text (Handle, Text.Replace (Environment.NewLine, string.Empty));
251                 }
252                 
253                 internal void SelectActiveControl ()
254                 {
255                         if (this.IsMdiContainer) {
256                                 mdi_container.SendFocusToActiveChild ();
257                                 return;
258                         }
259                                 
260                         if (this.ActiveControl == null) {
261                                 bool visible;
262
263                                 // This visible hack is to work around CanSelect always being false if one of the parents
264                                 // is not visible; and we by default create Form invisible...
265                                 visible = this.is_visible;
266                                 this.is_visible = true;
267
268                                 if (SelectNextControl (this, true, true, true, true) == false) {
269                                         Select (this);
270                                 }
271
272                                 this.is_visible = visible;
273                         } else {
274                                 Select (ActiveControl);
275                         }
276                 }
277                 
278                 private new void UpdateSizeGripVisible ()
279                 {
280                         // Following link explains when to show size grip:
281                         // http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=138687&SiteID=1
282                         // if SizeGripStyle.Auto, only shown if form is shown using ShowDialog and is sizable
283                         // if SizeGripStyle.Show, only shown if form is sizable
284                         
285                         bool show = false;
286                         
287                         switch (size_grip_style) {
288                         case SizeGripStyle.Auto:
289                                 show = is_modal && (form_border_style == FormBorderStyle.Sizable || form_border_style == FormBorderStyle.SizableToolWindow);
290                                 break;
291                         case SizeGripStyle.Hide:
292                                 show = false;
293                                 break;
294                         case SizeGripStyle.Show:
295                                 show = (form_border_style == FormBorderStyle.Sizable || form_border_style == FormBorderStyle.SizableToolWindow);
296                                 break;
297                         }
298                         
299                         if (!show) {
300                                 if (size_grip != null && size_grip.Visible)
301                                         size_grip.Visible = false;
302                         } else {
303                                 if (size_grip == null) {
304                                         size_grip = new SizeGrip (this);
305                                         size_grip.Virtual = true;
306                                         size_grip.FillBackground = false;
307                                 }
308                                 size_grip.Visible = true;
309                         }
310                 }
311                 
312                 internal void ChangingParent (Control new_parent)
313                 {
314                         if (IsMdiChild) {
315                                 return;
316                         }
317                         
318                         bool recreate_necessary = false;
319                         
320                         if (new_parent == null) {
321                                 window_manager = null;
322                         } else if (new_parent is MdiClient) {
323                                 window_manager = new MdiWindowManager (this, (MdiClient) new_parent);
324                         } else {
325                                 window_manager = new FormWindowManager (this);
326                                 recreate_necessary = true;
327                         }
328                         
329                         if (recreate_necessary) {
330                                 if (IsHandleCreated) {
331                                         if (new_parent != null && new_parent.IsHandleCreated) {
332                                                 RecreateHandle ();
333                                         } else {
334                                                 DestroyHandle ();
335                                         }
336                                 }
337                         } else {
338                                 if (IsHandleCreated) {
339                                         IntPtr new_handle = IntPtr.Zero;
340                                         if (new_parent != null && new_parent.IsHandleCreated) {
341                                                 new_handle = new_parent.Handle;
342                                         }
343                                         XplatUI.SetParent (Handle, new_handle);
344                                 }
345                         }
346                 
347                         if (window_manager != null) {
348                                 window_manager.UpdateWindowState (window_state, window_state, true);
349                         }
350                 }
351
352                 internal override bool FocusInternal (bool skip_check)
353                 {
354                         if (IsMdiChild) {
355                                 // MS always creates handles when Focus () is called for mdi clients.
356                                 if (!IsHandleCreated)
357                                         CreateHandle ();
358                         } 
359                         return base.FocusInternal (skip_check);
360                 }
361                 #endregion      // Private & Internal Methods
362
363                 #region Public Classes
364                 [ComVisible (false)]
365                 public new class ControlCollection : Control.ControlCollection {
366                         Form    form_owner;
367
368                         public ControlCollection(Form owner) : base(owner) {
369                                 this.form_owner = owner;
370                         }
371
372                         public override void Add(Control value) {
373                                 if (Contains (value))
374                                         return;
375                                 AddToList (value);
376                                 ((Form)value).owner=form_owner;
377                         }
378
379                         public override void Remove(Control value) {
380                                 ((Form)value).owner = null;
381                                 base.Remove (value);
382                         }
383                 }
384                 #endregion      // Public Classes
385
386                 #region Public Constructor & Destructor
387                 public Form ()
388                 {
389                         SizeF current_scale = GetAutoScaleSize (Font);
390
391                         autoscale = true;
392                         autoscale_base_size = new Size ((int)Math.Round (current_scale.Width), (int)Math.Round(current_scale.Height));
393                         allow_transparency = false;
394                         closing = false;
395                         is_modal = false;
396                         dialog_result = DialogResult.None;
397                         start_position = FormStartPosition.WindowsDefaultLocation;
398                         form_border_style = FormBorderStyle.Sizable;
399                         window_state = FormWindowState.Normal;
400                         key_preview = false;
401                         opacity = 1D;
402                         menu = null;
403                         icon = default_icon;
404                         minimum_size = Size.Empty;
405                         maximum_size = Size.Empty;
406                         clientsize_set = Size.Empty;
407                         control_box = true;
408                         minimize_box = true;
409                         maximize_box = true;
410                         help_button = false;
411                         show_in_taskbar = true;
412                         is_visible = false;
413                         is_toplevel = true;
414                         size_grip_style = SizeGripStyle.Auto;
415                         maximized_bounds = Rectangle.Empty;
416                         default_maximized_bounds = Rectangle.Empty;
417                         owned_forms = new Form.ControlCollection(this);
418                         transparency_key = Color.Empty;
419                         CreateDockPadding ();
420                         InternalClientSize = new Size (this.Width - (SystemInformation.FrameBorderSize.Width * 2), this.Height - (SystemInformation.FrameBorderSize.Height * 2) - SystemInformation.CaptionHeight);
421                         restore_bounds = Bounds;
422                 }
423                 #endregion      // Public Constructor & Destructor
424
425                 #region Public Static Properties
426
427                 public static Form ActiveForm {
428                         get {
429                                 Control active;
430
431                                 active = FromHandle(XplatUI.GetActive());
432
433                                 if (active != null) {
434                                         if ( !(active is Form)) {
435                                                 Control parent;
436
437                                                 parent = active.Parent;
438                                                 while (parent != null) {
439                                                         if (parent is Form) {
440                                                                 return (Form)parent;
441                                                         }
442                                                         parent = parent.Parent;
443                                                 }
444                                         } else {
445                                                 return (Form)active;
446                                         }
447                                 }
448                                 return null;
449                         }
450                 }
451
452                 #endregion      // Public Static Properties
453
454                 #region Public Instance Properties
455                 [DefaultValue(null)]
456                 public IButtonControl AcceptButton {
457                         get {
458                                 return accept_button;
459                         }
460
461                         set {
462                                 if (accept_button != null)
463                                         accept_button.NotifyDefault (false);
464
465                                 accept_button = value;
466                                 if (accept_button != null)
467                                         accept_button.NotifyDefault (true);
468
469                                 CheckAcceptButton ();
470                         }
471                 }
472
473                 [Browsable(false)]
474                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
475                 public bool AllowTransparency {
476                         get {
477                                 return allow_transparency;
478                         }
479
480                         set {
481                                 if (value == allow_transparency) {
482                                         return;
483                                 }
484
485                                 allow_transparency = value;
486
487                                 if (value) {
488                                         if (IsHandleCreated) {
489                                                 if ((XplatUI.SupportsTransparency() & TransparencySupport.Set) != 0) {
490                                                         XplatUI.SetWindowTransparency(Handle, Opacity, TransparencyKey);
491                                                 }
492                                         } else {
493                                                 UpdateStyles(); // Remove the WS_EX_LAYERED style
494                                         }
495                                 }
496                         }
497                 }
498
499                 [Browsable (false)]
500                 [EditorBrowsable (EditorBrowsableState.Never)]
501                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
502                 [Obsolete ("This property has been deprecated in favor of AutoScaleMode.")]
503                 [MWFCategory("Layout")]
504                 public bool AutoScale {
505                         get {
506                                 return autoscale;
507                         }
508
509                         set {
510                                 if (value)
511                                         AutoScaleMode = AutoScaleMode.None;
512
513                                 autoscale = value;
514                         }
515                 }
516
517                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
518                 [EditorBrowsable(EditorBrowsableState.Never)]
519                 [Localizable(true)]
520                 [Browsable(false)]
521                 public virtual Size AutoScaleBaseSize {
522                         get {
523                                 return autoscale_base_size;
524                         }
525                         [MonoTODO ("Setting this is probably unintentional and can cause Forms to be improperly sized.  See http://www.mono-project.com/FAQ:_Winforms#My_forms_are_sized_improperly for details.")]
526                         set {
527                                 autoscale_base_size = value;
528                                 autoscale_base_size_set = true;
529                         }
530                 }
531
532                 [Localizable(true)]
533                 public override bool AutoScroll {
534                         get {
535                                 return base.AutoScroll;
536                         }
537                         set {
538                                 base.AutoScroll = value;
539                         }
540                 }
541
542                 internal bool ShouldSerializeAutoScroll ()
543                 {
544                         return this.AutoScroll != false;
545                 }
546
547                 [Browsable (true)]
548                 [EditorBrowsable (EditorBrowsableState.Always)]
549                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Visible)]
550                 public override bool AutoSize {
551                         get { return base.AutoSize; }
552                         set { 
553                                 if (base.AutoSize != value) {
554                                         base.AutoSize = value;
555                                         PerformLayout (this, "AutoSize");
556                                 }
557                         }
558                 }
559
560                 internal bool ShouldSerializeAutoSize ()
561                 {
562                         return this.AutoSize != false;
563                 }
564                 
565                 [Browsable (true)]
566                 [Localizable (true)]
567                 [DefaultValue (AutoSizeMode.GrowOnly)]
568                 public AutoSizeMode AutoSizeMode {
569                         get { return base.GetAutoSizeMode (); }
570                         set { 
571                                 if (base.GetAutoSizeMode () != value) {
572                                         if (!Enum.IsDefined (typeof (AutoSizeMode), value))
573                                                 throw new InvalidEnumArgumentException (string.Format ("Enum argument value '{0}' is not valid for AutoSizeMode", value));
574
575                                         base.SetAutoSizeMode (value);
576                                         PerformLayout (this, "AutoSizeMode");
577                                 }
578                         }
579                 }
580
581                 [Browsable (true)]
582                 [EditorBrowsable (EditorBrowsableState.Always)]
583                 public override AutoValidate AutoValidate {
584                         get { return base.AutoValidate; }
585                         set { base.AutoValidate = value; }
586                 }
587
588                 public override Color BackColor {
589                         get {
590                                 /* we don't let parents override our
591                                  default background color for forms.
592                                  this fixes the default color for mdi
593                                  children. */
594                                 if (background_color.IsEmpty)
595                                         return DefaultBackColor;
596                                 else
597                                         return background_color;
598                         }
599                         set {
600                                 base.BackColor = value;
601                         }
602                 }
603
604                 [DefaultValue(null)]
605                 public IButtonControl CancelButton {
606                         get {
607                                 return cancel_button;
608                         }
609
610                         set {
611                                 cancel_button = value;
612                                 if (cancel_button != null && cancel_button.DialogResult == DialogResult.None)
613                                         cancel_button.DialogResult = DialogResult.Cancel;
614                         }
615                 }
616
617                 // new property so we can change the DesignerSerializationVisibility
618                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
619                 [Localizable(true)]
620                 public new Size ClientSize {
621                         get { return base.ClientSize; }
622                         set {
623                                 is_clientsize_set = true;
624                                 base.ClientSize = value;
625                         }
626                 }
627
628                 [DefaultValue(true)]
629                 [MWFCategory("Window Style")]
630                 public bool ControlBox {
631                         get {
632                                 return control_box;
633                         }
634
635                         set {
636                                 if (control_box != value) {
637                                         control_box = value;
638                                         UpdateStyles();
639                                 }
640                         }
641                 }
642
643                 [Browsable(false)]
644                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
645                 public Rectangle DesktopBounds {
646                         get {
647                                 return new Rectangle(Location, Size);
648                         }
649
650                         set {
651                                 Bounds = value;
652                         }
653                 }
654
655                 [Browsable(false)]
656                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
657                 public Point DesktopLocation {
658                         get {
659                                 return Location;
660                         }
661
662                         set {
663                                 Location = value;
664                         }
665                 }
666
667                 [Browsable(false)]
668                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
669                 public DialogResult DialogResult {
670                         get {
671                                 return dialog_result;
672                         }
673
674                         set {
675                                 if (value < DialogResult.None || value > DialogResult.No)
676                                         throw new InvalidEnumArgumentException ("value", (int) value, 
677                                                         typeof (DialogResult));
678
679                                 dialog_result = value;
680                                 if (dialog_result != DialogResult.None && is_modal)
681                                         RaiseCloseEvents (false, false); // .Net doesn't send WM_CLOSE here.
682                         }
683                 }
684
685                 [DefaultValue(FormBorderStyle.Sizable)]
686                 [DispId(-504)]
687                 [MWFCategory("Appearance")]
688                 public FormBorderStyle FormBorderStyle {
689                         get {
690                                 return form_border_style;
691                         }
692                         set {
693                                 form_border_style = value;
694
695                                 if (window_manager == null) {
696                                         if (IsHandleCreated) {
697                                                 XplatUI.SetBorderStyle(window.Handle, form_border_style);
698                                         }
699                                 } else {
700                                         window_manager.UpdateBorderStyle (value);
701                                 }
702
703                                 Size current_client_size = ClientSize;
704                                 UpdateStyles();
705                                 
706                                 if (this.IsHandleCreated) {
707                                         this.Size = InternalSizeFromClientSize (current_client_size);
708                                         XplatUI.InvalidateNC (this.Handle);
709                                 } else if (is_clientsize_set) {
710                                         this.Size = InternalSizeFromClientSize (current_client_size);
711                                 }
712                         }
713                 }
714
715                 [DefaultValue(false)]
716                 [MWFCategory("Window Style")]
717                 public bool HelpButton {
718                         get {
719                                 return help_button;
720                         }
721
722                         set {
723                                 if (help_button != value) {
724                                         help_button = value;
725                                         UpdateStyles();
726                                 }
727                         }
728                 }
729
730                 [Localizable(true)]
731                 [AmbientValue(null)]
732                 [MWFCategory("Window Style")]
733                 public Icon Icon {
734                         get {
735                                 return icon;
736                         }
737
738                         set {
739                                 if (value == null)
740                                         value = default_icon;
741                                 if (icon == value)
742                                         return;
743                                 icon = value;
744                                 if (IsHandleCreated)
745                                         XplatUI.SetIcon (Handle, icon);
746                         }
747                 }
748
749                 internal bool ShouldSerializeIcon ()
750                 {
751                         return this.Icon != default_icon;
752                 }
753
754                 [Browsable(false)]
755                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
756                 public bool IsMdiChild {
757                         get {
758                                 return mdi_parent != null;
759                         }
760                 }
761
762                 [DefaultValue(false)]
763                 [MWFCategory("Window Style")]
764                 public bool IsMdiContainer {
765                         get {
766                                 return mdi_container != null;
767                         }
768
769                         set {
770                                 if (value && mdi_container == null) {
771                                         mdi_container = new MdiClient ();
772                                         Controls.Add(mdi_container);
773                                         ControlAdded += new ControlEventHandler (ControlAddedHandler);
774                                         mdi_container.SendToBack ();
775                                         mdi_container.SetParentText (true);
776                                 } else if (!value && mdi_container != null) {
777                                         Controls.Remove(mdi_container);
778                                         mdi_container = null;
779                                 }
780                         }
781                 }
782
783                 [Browsable(false)]
784                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
785                 public Form ActiveMdiChild {
786                         get {
787                                 if (!IsMdiContainer)
788                                         return null;
789                                 return (Form) mdi_container.ActiveMdiChild;
790                         }
791                 }
792
793                 [Browsable(false)]
794                 [EditorBrowsable(EditorBrowsableState.Advanced)]
795                 public bool IsRestrictedWindow {
796                         get {
797                                 return false;
798                         }
799                 }
800
801                 [DefaultValue(false)]
802                 public bool KeyPreview {
803                         get {
804                                 return key_preview;
805                         }
806
807                         set {
808                                 key_preview = value;
809                         }
810                 }
811
812                 [DefaultValue (null)]
813                 [TypeConverter (typeof (ReferenceConverter))]
814                 public MenuStrip MainMenuStrip {
815                         get { return this.main_menu_strip; }
816                         set { 
817                                 if (this.main_menu_strip != value) {
818                                         this.main_menu_strip = value;
819                                         this.main_menu_strip.RefreshMdiItems ();
820                                 }
821                         }
822                 }
823                 
824                 [EditorBrowsable (EditorBrowsableState.Never)]
825                 [Browsable (false)]
826                 public new Padding Margin {
827                         get { return base.Margin; }
828                         set { base.Margin = value; }
829                 }
830
831                 [DefaultValue(true)]
832                 [MWFCategory("Window Style")]
833                 public bool MaximizeBox {
834                         get {
835                                 return maximize_box;
836                         }
837                         set {
838                                 if (maximize_box != value) {
839                                         maximize_box = value;
840                                         UpdateStyles();
841                                 }
842                         }
843                 }
844
845                 [DefaultValue(typeof (Size),"0, 0")]
846                 [Localizable(true)]
847                 [RefreshProperties(RefreshProperties.Repaint)]
848                 [MWFCategory("Layout")]
849                 public override Size MaximumSize {
850                         get {
851                                 return maximum_size;
852                         }
853
854                         set {
855                                 if (maximum_size != value) {
856                                         maximum_size = value;
857
858                                         // If this is smaller than the min, adjust the min
859                                         if (!minimum_size.IsEmpty) {
860                                                 if (maximum_size.Width <= minimum_size.Width)
861                                                         minimum_size.Width = maximum_size.Width;
862                                                 if (maximum_size.Height <= minimum_size.Height)
863                                                         minimum_size.Height = maximum_size.Height;
864                                         }
865                                                 
866                                         OnMaximumSizeChanged(EventArgs.Empty);
867                                         if (IsHandleCreated) {
868                                                 XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
869                                         }
870                                 }
871                         }
872                 }
873
874                 [Browsable(false)]
875                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
876                 public Form[] MdiChildren {
877                         get {
878                                 if (mdi_container != null)
879                                         return mdi_container.MdiChildren;
880                                 else
881                                         return new Form[0];
882                         }
883                 }
884
885                 [Browsable(false)]
886                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
887                 public Form MdiParent {
888                         get {
889                                 return mdi_parent;
890                         }
891
892                         set {
893                                 if (value == mdi_parent)
894                                         return;
895
896                                 if (value != null && !value.IsMdiContainer)
897                                         throw new ArgumentException ("Form that was specified to be "
898                                                 + "the MdiParent for this form is not an MdiContainer.");
899
900                                 if (mdi_parent != null) {
901                                         mdi_parent.MdiContainer.Controls.Remove (this);
902                                 }
903
904                                 if (value != null) {
905                                         mdi_parent = value;
906                                         if (window_manager == null) {
907                                                 window_manager = new MdiWindowManager (this, mdi_parent.MdiContainer);
908                                         }
909                                         
910                                         mdi_parent.MdiContainer.Controls.Add (this);
911                                         mdi_parent.MdiContainer.Controls.SetChildIndex (this, 0);
912                                         
913                                         if (IsHandleCreated)
914                                                 RecreateHandle ();
915                                 } else if (mdi_parent != null) {
916                                         mdi_parent = null;
917
918                                         // Create a new window manager
919                                         window_manager = null;
920                                         FormBorderStyle = form_border_style;
921
922                                         if (IsHandleCreated)
923                                                 RecreateHandle ();
924                                 }
925                                 is_toplevel = mdi_parent == null;
926                         }
927                 }
928
929                 internal MdiClient MdiContainer {
930                         get { return mdi_container; }
931                 }
932
933                 internal InternalWindowManager WindowManager {
934                         get { return window_manager; }
935                 }
936
937                 [Browsable (false)]
938                 [TypeConverter (typeof (ReferenceConverter))]
939                 [DefaultValue(null)]
940                 [MWFCategory("Window Style")]
941                 public MainMenu Menu {
942                         get {
943                                 return menu;
944                         }
945
946                         set {
947                                 if (menu != value) {
948                                         menu = value;
949
950                                         if (menu != null && !IsMdiChild) {
951                                                 menu.SetForm (this);
952
953                                                 if (IsHandleCreated) {
954                                                         XplatUI.SetMenu (window.Handle, menu);
955                                                 }
956
957                                                 if (clientsize_set != Size.Empty) {
958                                                         SetClientSizeCore(clientsize_set.Width, clientsize_set.Height);
959                                                 } else {
960                                                         UpdateBounds (bounds.X, bounds.Y, bounds.Width, bounds.Height, ClientSize.Width, ClientSize.Height - 
961                                                                 ThemeEngine.Current.CalcMenuBarSize (DeviceContext, menu, ClientSize.Width));
962                                                 }
963                                         } else
964                                                 UpdateBounds ();
965
966                                         // UIA Framework Event: Menu Changed
967                                         OnUIAMenuChanged (EventArgs.Empty);
968                                 }
969                         }
970                 }
971
972                 [Browsable(false)]
973                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
974                 [EditorBrowsable(EditorBrowsableState.Advanced)]
975                 public MainMenu MergedMenu {
976                         get {
977                                 if (!IsMdiChild || window_manager == null)
978                                         return null;
979                                 return ((MdiWindowManager) window_manager).MergedMenu;
980                         }
981                 }
982
983                 // This is the menu in display and being used because of merging this can
984                 // be different then the menu that is actually assosciated with the form
985                 internal MainMenu ActiveMenu {
986                         get {
987                                 if (IsMdiChild)
988                                         return null;
989
990                                 if (IsMdiContainer && mdi_container.Controls.Count > 0 &&
991                                                 ((Form) mdi_container.Controls [0]).WindowState == FormWindowState.Maximized) {
992                                         MdiWindowManager wm = (MdiWindowManager) ((Form) mdi_container.Controls [0]).WindowManager;
993                                         return wm.MaximizedMenu;
994                                 }
995
996                                 Form amc = ActiveMdiChild;
997                                 if (amc == null || amc.Menu == null)
998                                         return menu;
999                                 return amc.MergedMenu;
1000                         }
1001                 }
1002
1003                 internal MdiWindowManager ActiveMaximizedMdiChild {
1004                         get {
1005                                 Form child = ActiveMdiChild;
1006                                 if (child == null)
1007                                         return null;
1008                                 if (child.WindowManager == null || child.window_state != FormWindowState.Maximized)
1009                                         return null;
1010                                 return (MdiWindowManager) child.WindowManager;
1011                         }
1012                 }
1013
1014                 [DefaultValue(true)]
1015                 [MWFCategory("Window Style")]
1016                 public bool MinimizeBox {
1017                         get {
1018                                 return minimize_box;
1019                         }
1020                         set {
1021                                 if (minimize_box != value) {
1022                                         minimize_box = value;
1023                                         UpdateStyles();
1024                                 }
1025                         }
1026                 }
1027
1028                 [Localizable(true)]
1029                 [RefreshProperties(RefreshProperties.Repaint)]
1030                 [MWFCategory("Layout")]
1031                 public override Size MinimumSize {
1032                         get {
1033                                 return minimum_size;
1034                         }
1035
1036                         set {
1037                                 if (minimum_size != value) {
1038                                         minimum_size = value;
1039
1040                                         // If this is bigger than the max, adjust the max
1041                                         if (!maximum_size.IsEmpty) {
1042                                                 if (minimum_size.Width >= maximum_size.Width)
1043                                                         maximum_size.Width = minimum_size.Width;
1044                                                 if (minimum_size.Height >= maximum_size.Height)
1045                                                         maximum_size.Height = minimum_size.Height;
1046                                         }
1047                                         
1048                                         if ((Size.Width < value.Width) || (Size.Height < value.Height)) {
1049                                                 Size = new Size(Math.Max(Size.Width, value.Width), Math.Max(Size.Height, value.Height));
1050                                         }
1051   
1052
1053                                         OnMinimumSizeChanged(EventArgs.Empty);
1054                                         if (IsHandleCreated) {
1055                                                 XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
1056                                         }
1057                                 }
1058                         }
1059                 }
1060
1061                 [Browsable(false)]
1062                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1063                 public bool Modal  {
1064                         get {
1065                                 return is_modal;
1066                         }
1067                 }
1068
1069                 [DefaultValue(1D)]
1070                 [TypeConverter(typeof(OpacityConverter))]
1071                 [MWFCategory("Window Style")]
1072                 public double Opacity {
1073                         get {
1074                                 if (IsHandleCreated) {
1075                                         if ((XplatUI.SupportsTransparency () & TransparencySupport.Get) != 0)
1076                                                 return XplatUI.GetWindowTransparency (Handle);
1077                                 }
1078
1079                                 return opacity;
1080                         }
1081
1082                         set {
1083                                 opacity = value;
1084
1085                                 if (opacity < 0)
1086                                         opacity = 0;
1087
1088                                 if (opacity > 1)
1089                                         opacity = 1;
1090
1091                                 AllowTransparency = true;
1092
1093                                 if (IsHandleCreated) {
1094                                         UpdateStyles();
1095                                         if ((XplatUI.SupportsTransparency () & TransparencySupport.Set) != 0)
1096                                                 XplatUI.SetWindowTransparency(Handle, opacity, TransparencyKey);
1097                                 }
1098                         }
1099                 }
1100                         
1101
1102                 [Browsable(false)]
1103                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1104                 public Form[] OwnedForms {
1105                         get {
1106                                 Form[] form_list;
1107
1108                                 form_list = new Form[owned_forms.Count];
1109
1110                                 for (int i=0; i<owned_forms.Count; i++) {
1111                                         form_list[i] = (Form)owned_forms[i];
1112                                 }
1113
1114                                 return form_list;
1115                         }
1116                 }
1117
1118                 [Browsable(false)]
1119                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1120                 public Form Owner {
1121                         get {
1122                                 return owner;
1123                         }
1124
1125                         set {
1126                                 if (owner != value) {
1127                                         if (owner != null) {
1128                                                 owner.RemoveOwnedForm(this);
1129                                         }
1130                                         owner = value;
1131                                         if (owner != null)
1132                                                 owner.AddOwnedForm(this);
1133                                         if (IsHandleCreated) {
1134                                                 if (owner != null && owner.IsHandleCreated) {
1135                                                         XplatUI.SetOwner(this.window.Handle, owner.window.Handle);
1136                                                 } else {
1137                                                         XplatUI.SetOwner(this.window.Handle, IntPtr.Zero);
1138                                                 }
1139                                         }
1140                                 }
1141                         }
1142                 }
1143
1144                 [Browsable (false)]
1145                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1146                 public Rectangle RestoreBounds {
1147                         get { return restore_bounds; }
1148                 }
1149                 
1150                 [Localizable (true)]
1151                 [DefaultValue (false)]
1152                 public virtual bool RightToLeftLayout {
1153                         get { return this.right_to_left_layout; }
1154                         set { this.right_to_left_layout = value; }
1155                 }
1156                 
1157                 [DefaultValue (true)]
1158                 public bool ShowIcon {
1159                         get { return this.show_icon; }
1160                         set {
1161                                 if (this.show_icon != value ) {
1162                                         this.show_icon = value;
1163                                         UpdateStyles ();
1164                                         
1165                                         if (IsHandleCreated) {
1166                                                 XplatUI.SetIcon (this.Handle, value == true ? this.Icon : null);
1167                                                 XplatUI.InvalidateNC (this.Handle);
1168                                         }
1169                                 }
1170                         }
1171                 }
1172         
1173                 [DefaultValue(true)]
1174                 [MWFCategory("Window Style")]
1175                 public bool ShowInTaskbar {
1176                         get {
1177                                 return show_in_taskbar;
1178                         }
1179                         set {
1180                                 if (show_in_taskbar != value) {
1181                                         show_in_taskbar = value;
1182                                         if (IsHandleCreated) {
1183                                                 RecreateHandle();
1184                                         }
1185                                         UpdateStyles();
1186                                 }
1187                         }
1188                 }
1189
1190                 // new property so we can set the DesignerSerializationVisibility
1191                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1192                 [Localizable(false)]
1193                 public new Size Size {
1194                         get { return base.Size; }
1195                         set { base.Size = value; }
1196                 }
1197
1198                 [DefaultValue(SizeGripStyle.Auto)]
1199                 [MWFCategory("Window Style")]
1200                 public SizeGripStyle SizeGripStyle {
1201                         get {
1202                                 return size_grip_style;
1203                         }
1204
1205                         set {
1206                                 size_grip_style = value;
1207                                 UpdateSizeGripVisible ();
1208                         }
1209                 }
1210
1211                 [DefaultValue(FormStartPosition.WindowsDefaultLocation)]
1212                 [Localizable(true)]
1213                 [MWFCategory("Layout")]
1214                 public FormStartPosition StartPosition {
1215                         get {
1216                                 return start_position;
1217                         }
1218
1219                         set {
1220                                 start_position = value;
1221                         }
1222                 }
1223
1224                 // new property so we can set EditorBrowsable to never
1225                 [Browsable(false)]
1226                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1227                 [EditorBrowsable(EditorBrowsableState.Never)]
1228                 public new int TabIndex {
1229                         get { return base.TabIndex; }
1230                         set { base.TabIndex = value; }
1231                 }
1232
1233                 [Browsable(false)]
1234                 [DefaultValue (true)]
1235                 [DispIdAttribute (-516)]
1236                 [EditorBrowsable(EditorBrowsableState.Never)]
1237                 public new bool TabStop {
1238                         get { return base.TabStop; }
1239                         set { base.TabStop = value; }
1240                 }
1241
1242                 [Browsable(false)]
1243                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1244                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1245                 public bool TopLevel {
1246                         get {
1247                                 return GetTopLevel();
1248                         }
1249
1250                         set {
1251                                 if (!value && IsMdiContainer)
1252                                         throw new ArgumentException ("MDI Container forms must be top level.");
1253                                 SetTopLevel(value);
1254                         }
1255                 }
1256
1257                 [DefaultValue(false)]
1258                 [MWFCategory("Window Style")]
1259                 public bool TopMost {
1260                         get {
1261                                 return topmost;
1262                         }
1263
1264                         set {
1265                                 if (topmost != value) {
1266                                         topmost = value;
1267                                         if (IsHandleCreated)
1268                                                 XplatUI.SetTopmost(window.Handle, value);
1269
1270                                         // UIA Framework: Raises internal event
1271                                         OnUIATopMostChanged ();
1272                                 }
1273                         }
1274                 }
1275
1276                 [MWFCategory("Window Style")]
1277                 public Color TransparencyKey {
1278                         get {
1279                                 return transparency_key;
1280                         }
1281
1282                         set {
1283                                 transparency_key = value;
1284
1285                                 AllowTransparency = true;
1286                                 UpdateStyles();
1287                                 if (IsHandleCreated && (XplatUI.SupportsTransparency () & TransparencySupport.Set) != 0)
1288                                         XplatUI.SetWindowTransparency(Handle, Opacity, transparency_key);
1289                         }
1290                 }
1291
1292                 internal bool ShouldSerializeTransparencyKey ()
1293                 {
1294                         return this.TransparencyKey != Color.Empty;
1295                 }
1296
1297                 [DefaultValue(FormWindowState.Normal)]
1298                 [MWFCategory("Layout")]
1299                 public FormWindowState WindowState {
1300                         get {
1301                                 // Don't actually rely on the WM until we've been shown
1302                                 if (IsHandleCreated && shown_raised) {
1303
1304                                         if (window_manager != null)
1305                                                 return window_manager.GetWindowState ();
1306
1307                                         FormWindowState new_state = XplatUI.GetWindowState(Handle);
1308                                         if (new_state != (FormWindowState)(-1))
1309                                                 window_state = new_state;
1310                                 }
1311
1312                                 return window_state;
1313                         }
1314
1315                         set {
1316                                 FormWindowState old_state = window_state;
1317                                 window_state = value;
1318                                 if (IsHandleCreated && shown_raised) {
1319
1320                                         if (window_manager != null) {
1321                                                 window_manager.SetWindowState (old_state, value);
1322                                                 return;
1323                                         }
1324
1325                                         XplatUI.SetWindowState(Handle, value);
1326                                 }
1327
1328                                 // UIA Framework: Raises internal event
1329                                 if (old_state != window_state) 
1330                                         OnUIAWindowStateChanged ();
1331                         }
1332                 }
1333
1334                 #endregion      // Public Instance Properties
1335
1336                 #region Protected Instance Properties
1337                 protected override CreateParams CreateParams {
1338                         get {
1339                                 CreateParams cp = new CreateParams ();
1340
1341                                 if (Text != null)
1342                                         cp.Caption = Text.Replace (Environment.NewLine, string.Empty);
1343                                 
1344                                 cp.ClassName = XplatUI.GetDefaultClassName (GetType ());
1345                                 cp.ClassStyle = 0;
1346                                 cp.Style = 0;
1347                                 cp.ExStyle = 0;
1348                                 cp.Param = 0;
1349                                 cp.Parent = IntPtr.Zero;
1350                                 cp.menu = ActiveMenu;
1351                                 cp.control = this;
1352
1353                                 if (((Parent != null || !TopLevel) && !IsMdiChild)) {
1354                                         // Parented forms and non-toplevel forms always gets the specified location, no matter what
1355                                         cp.X = Left;
1356                                         cp.Y = Top;
1357                                 } else {
1358                                         switch (start_position) {
1359                                         case FormStartPosition.Manual:
1360                                                 cp.X = Left;
1361                                                 cp.Y = Top;
1362                                                 break;
1363                                         case FormStartPosition.CenterScreen:
1364                                                 if (IsMdiChild) {
1365                                                         cp.X = Math.Max ((MdiParent.mdi_container.ClientSize.Width - Width) / 2, 0);
1366                                                         cp.Y = Math.Max ((MdiParent.mdi_container.ClientSize.Height - Height) / 2, 0);
1367                                                 } else {
1368                                                         cp.X = Math.Max ((Screen.PrimaryScreen.WorkingArea.Width - Width) / 2, 0);
1369                                                         cp.Y = Math.Max ((Screen.PrimaryScreen.WorkingArea.Height - Height) / 2, 0);
1370                                                 }
1371                                                 break;
1372                                         case FormStartPosition.CenterParent:
1373                                         case FormStartPosition.WindowsDefaultBounds:
1374                                         case FormStartPosition.WindowsDefaultLocation:
1375                                                 cp.X = int.MinValue;
1376                                                 cp.Y = int.MinValue;
1377                                                 break;
1378                                         }
1379                                 }
1380                                 cp.Width = Width;
1381                                 cp.Height = Height;
1382
1383                                 cp.Style = (int)(WindowStyles.WS_CLIPCHILDREN);
1384                                 if (!Modal) {
1385                                         cp.WindowStyle |= WindowStyles.WS_CLIPSIBLINGS;
1386                                 }
1387
1388                                 if (Parent != null && Parent.IsHandleCreated) {
1389                                         cp.Parent = Parent.Handle;
1390                                         cp.Style |= (int) WindowStyles.WS_CHILD;
1391                                 }
1392
1393                                 if (IsMdiChild) {
1394                                         cp.Style |= (int)(WindowStyles.WS_CHILD | WindowStyles.WS_CAPTION);
1395                                         if (Parent != null) {
1396                                                 cp.Parent = Parent.Handle;
1397                                         }
1398
1399                                         cp.ExStyle |= (int) (WindowExStyles.WS_EX_WINDOWEDGE | WindowExStyles.WS_EX_MDICHILD);
1400
1401                                         switch (FormBorderStyle) {
1402                                         case FormBorderStyle.None:
1403                                                 break;
1404                                         case FormBorderStyle.FixedToolWindow:
1405                                         case FormBorderStyle.SizableToolWindow:
1406                                                 cp.ExStyle |= (int) WindowExStyles.WS_EX_TOOLWINDOW;
1407                                                 goto default;
1408                                         default:
1409                                                 cp.Style |= (int) WindowStyles.WS_OVERLAPPEDWINDOW;
1410                                                 break;
1411                                         }
1412                                         
1413                                 } else {
1414                                         switch (FormBorderStyle) {
1415                                                 case FormBorderStyle.Fixed3D: {
1416                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1417                                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_CLIENTEDGE; 
1418                                                         break;
1419                                                 }
1420
1421                                                 case FormBorderStyle.FixedDialog: {
1422                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1423                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_DLGMODALFRAME | WindowExStyles.WS_EX_CONTROLPARENT);
1424                                                         break;
1425                                                 }
1426
1427                                                 case FormBorderStyle.FixedSingle: {
1428                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1429                                                         break;
1430                                                 }
1431
1432                                                 case FormBorderStyle.FixedToolWindow: { 
1433                                                         cp.Style |= (int)(WindowStyles.WS_CAPTION | WindowStyles.WS_BORDER);
1434                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_TOOLWINDOW);
1435                                                         break;
1436                                                 }
1437
1438                                                 case FormBorderStyle.Sizable: {
1439                                                         cp.Style |= (int)(WindowStyles.WS_BORDER | WindowStyles.WS_THICKFRAME | WindowStyles.WS_CAPTION); 
1440                                                         break;
1441                                                 }
1442
1443                                                 case FormBorderStyle.SizableToolWindow: {
1444                                                         cp.Style |= (int)(WindowStyles.WS_BORDER | WindowStyles.WS_THICKFRAME | WindowStyles.WS_CAPTION);
1445                                                         cp.ExStyle |= (int)(WindowExStyles.WS_EX_TOOLWINDOW);
1446                                                         break;
1447                                                 }
1448
1449                                                 case FormBorderStyle.None: {
1450                                                         break;
1451                                                 }
1452                                         }
1453                                 }
1454
1455                                 switch(window_state) {
1456                                         case FormWindowState.Maximized: {
1457                                                 cp.Style |= (int)WindowStyles.WS_MAXIMIZE;
1458                                                 break;
1459                                         }
1460
1461                                         case FormWindowState.Minimized: {
1462                                                 cp.Style |= (int)WindowStyles.WS_MINIMIZE;
1463                                                 break;
1464                                         }
1465                                 }
1466
1467                                 if (TopMost) {
1468                                         cp.ExStyle |= (int) WindowExStyles.WS_EX_TOPMOST;
1469                                 }
1470
1471                                 if (ShowInTaskbar) {
1472                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_APPWINDOW;
1473                                 }
1474
1475                                 if (MaximizeBox) {
1476                                         cp.Style |= (int)WindowStyles.WS_MAXIMIZEBOX;
1477                                 }
1478
1479                                 if (MinimizeBox) {
1480                                         cp.Style |= (int)WindowStyles.WS_MINIMIZEBOX;
1481                                 }
1482
1483                                 if (ControlBox) {
1484                                         cp.Style |= (int)WindowStyles.WS_SYSMENU;
1485                                 }
1486
1487                                 if (!this.show_icon) {
1488                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_DLGMODALFRAME;
1489                                 }
1490
1491                                 cp.ExStyle |= (int)WindowExStyles.WS_EX_CONTROLPARENT;
1492
1493                                 if (HelpButton && !MaximizeBox && !MinimizeBox) {
1494                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_CONTEXTHELP;
1495                                 }
1496
1497                                 // bug 80775:
1498                                 //don't set WS_VISIBLE if we're changing visibility. We can't create forms visible, 
1499                                 //since we have to set the owner before making the form visible 
1500                                 //(otherwise Win32 will do strange things with task bar icons). 
1501                                 //The problem is that we set the internal is_visible to true before creating the control, 
1502                                 //so is_changing_visible_state is the only way of determining if we're 
1503                                 //in the process of creating the form due to setting Visible=true.
1504                                 //This works because SetVisibleCore explicitly makes the form visibile afterwards anyways.
1505                                 // bug 81957:
1506                                 //only do this when on Windows, since X behaves weirdly otherwise
1507                                 //modal windows appear below their parent/owner/ancestor.
1508                                 //(confirmed on several window managers, so it's not a wm bug).
1509                                 int p = (int) Environment.OSVersion.Platform;
1510                                 bool is_unix = (p == 128) || (p == 4) || (p == 6);
1511                                 if ((VisibleInternal && (is_changing_visible_state == 0 || is_unix)) || this.IsRecreating)
1512                                         cp.Style |= (int)WindowStyles.WS_VISIBLE;
1513
1514                                 if (opacity < 1.0 || TransparencyKey != Color.Empty) {
1515                                         cp.ExStyle |= (int)WindowExStyles.WS_EX_LAYERED;
1516                                 }
1517
1518                                 if (!is_enabled && context == null) {
1519                                         cp.Style |= (int)(WindowStyles.WS_DISABLED);
1520                                 }
1521
1522                                 if (!ControlBox && Text == string.Empty) {
1523                                         cp.WindowStyle &= ~WindowStyles.WS_DLGFRAME;
1524                                 }
1525                                 
1526                                 return cp;
1527                         }
1528                 }
1529
1530                 protected override ImeMode DefaultImeMode {
1531                         get {
1532                                 return ImeMode.NoControl;
1533                         }
1534                 }
1535
1536                 protected override Size DefaultSize {
1537                         get {
1538                                 return new Size (300, 300);
1539                         }
1540                 }
1541
1542                 protected Rectangle MaximizedBounds {
1543                         get {
1544                                 if (maximized_bounds != Rectangle.Empty) {
1545                                         return maximized_bounds;
1546                                 }
1547                                 return default_maximized_bounds;
1548                         }
1549
1550                         set {
1551                                 maximized_bounds = value;
1552                                 OnMaximizedBoundsChanged(EventArgs.Empty);
1553                                 if (IsHandleCreated) {
1554                                         XplatUI.SetWindowMinMax(Handle, maximized_bounds, minimum_size, maximum_size);
1555                                 }
1556                         }
1557                 }
1558                 
1559                 [Browsable (false)]
1560                 [MonoTODO ("Implemented for Win32, needs X11 implementation")]
1561                 protected virtual bool ShowWithoutActivation {
1562                         get { return false; }
1563                 }
1564                 #endregion      // Protected Instance Properties
1565
1566                 #region Public Static Methods
1567                 [EditorBrowsable(EditorBrowsableState.Never)]
1568                 [Obsolete ("This method has been deprecated.  Use AutoScaleDimensions instead")]
1569                 public static SizeF GetAutoScaleSize (Font font)
1570                 {
1571                         return XplatUI.GetAutoScaleSize(font);
1572                 }
1573
1574                 #endregion      // Public Static Methods
1575
1576                 #region Public Instance Methods
1577                                                  
1578                 public void Activate ()
1579                 {
1580                         if (IsHandleCreated) {
1581                                 if (IsMdiChild) {
1582                                         MdiParent.ActivateMdiChild (this);
1583                                 } else if (IsMdiContainer) {
1584                                         mdi_container.SendFocusToActiveChild ();
1585                                 } else {
1586                                         XplatUI.Activate(window.Handle);
1587                                 }
1588                         }
1589                 }
1590
1591                 public void AddOwnedForm(Form ownedForm) {
1592                         if (!owned_forms.Contains(ownedForm)) {
1593                                 owned_forms.Add(ownedForm);
1594                         }
1595                         ownedForm.Owner = this;
1596                 }
1597
1598                 public void Close () {
1599                         if (IsDisposed)
1600                                 return;
1601
1602                         if (!IsHandleCreated) {
1603                                 base.Dispose ();
1604                                 return;
1605                         }
1606  
1607                         if (Menu != null)
1608                                 XplatUI.SetMenu (window.Handle, null);
1609
1610                         XplatUI.SendMessage(this.Handle, Msg.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
1611
1612                         closed = true;
1613                 }
1614
1615                 public void LayoutMdi(MdiLayout value) {
1616                         if (mdi_container != null) {
1617                                 mdi_container.LayoutMdi(value);
1618                         }
1619                 }
1620
1621                 public void RemoveOwnedForm(Form ownedForm) {
1622                         owned_forms.Remove(ownedForm);
1623                 }
1624
1625                 public void SetDesktopBounds(int x, int y, int width, int height) {
1626                         DesktopBounds = new Rectangle(x, y, width, height);
1627                 }
1628
1629                 public void SetDesktopLocation(int x, int y) {
1630                         DesktopLocation = new Point(x, y);
1631                 }
1632
1633                 public void Show (IWin32Window owner)
1634                 {
1635                         if (owner == null)
1636                                 this.Owner = null;
1637                         else
1638                                 this.Owner = Control.FromHandle (owner.Handle).TopLevelControl as Form;
1639
1640                         if (owner == this)
1641                                 throw new InvalidOperationException ("The 'owner' cannot be the form being shown.");
1642
1643                         if (TopLevelControl != this) {
1644                                 throw new InvalidOperationException ("Forms that are not top level"
1645                                         + " forms cannot be displayed as a modal dialog. Remove the"
1646                                         + " form from any parent form before calling Show.");
1647                         }
1648
1649                         base.Show ();
1650                 }
1651
1652                 public DialogResult ShowDialog() {
1653                         return ShowDialog (null);
1654                 }
1655
1656                 public DialogResult ShowDialog(IWin32Window owner) {
1657                         Rectangle       area;
1658                         bool            confined;
1659                         IntPtr          capture_window;
1660
1661                         IWin32Window original_owner = owner;
1662                         Form owner_to_be = null;
1663
1664                         if ((owner == null) && (Application.MWFThread.Current.Context != null)) {
1665                                 IntPtr active = XplatUI.GetActive ();
1666                                 if (active != IntPtr.Zero) {
1667                                         owner = Control.FromHandle (active) as Form;
1668                                 }
1669                         }
1670
1671                         if (owner != null) {
1672                                 Control c = Control.FromHandle (owner.Handle);
1673                                 if (c != null)
1674                                         owner_to_be = c.TopLevelControl as Form;
1675                         }
1676
1677                         if (owner_to_be == this) {
1678                                 // Don't let a null owner become self-referential.  This has been observed,
1679                                 // but the circumstances are unclear.
1680                                 if (original_owner == null) {
1681                                         owner = null;
1682                                         owner_to_be = null;
1683                                 }
1684                                 else {
1685                                         throw new ArgumentException ("Forms cannot own themselves or their owners.", "owner");
1686                                 }
1687                         }
1688
1689                         if (is_modal) {
1690                                 throw new InvalidOperationException ("The form is already displayed as a modal dialog.");
1691                         }
1692
1693                         if (Visible) {
1694                                 throw new InvalidOperationException ("Forms that are already "
1695                                         + " visible cannot be displayed as a modal dialog. Set the"
1696                                         + " form's visible property to false before calling"
1697                                         + " ShowDialog.");
1698                         }
1699
1700                         if (!Enabled) {
1701                                 throw new InvalidOperationException ("Forms that are not enabled"
1702                                         + " cannot be displayed as a modal dialog. Set the form's"
1703                                         + " enabled property to true before calling ShowDialog.");
1704                         }
1705
1706                         if (TopLevelControl != this) {
1707                                 throw new InvalidOperationException ("Forms that are not top level"
1708                                         + " forms cannot be displayed as a modal dialog. Remove the"
1709                                         + " form from any parent form before calling ShowDialog.");
1710                         }
1711
1712                         if (owner_to_be != null)
1713                                 this.owner = owner_to_be;
1714                                 
1715                         // If our owner is topmost, we better be too, or else we'll show up under our owner
1716                         if (this.owner != null && this.owner.TopMost)
1717                                 this.TopMost = true;
1718                                 
1719                         #if broken
1720                         // Can't do this, will screw us in the modal loop
1721                         form_parent_window.Parent = this.owner;
1722                         #endif
1723
1724                         // Release any captures
1725                         XplatUI.GrabInfo(out capture_window, out confined, out area);
1726                         if (capture_window != IntPtr.Zero) {
1727                                 XplatUI.UngrabWindow(capture_window);
1728                         }
1729
1730                         var disable = new List<Form> ();
1731                         foreach (Form form in Application.OpenForms)
1732                                 if (form.Enabled)
1733                                         disable.Add (form);
1734                         foreach (Form form in disable){
1735                                 disabled_by_showdialog.Add (form);
1736                                 form.Enabled = false;
1737                         }
1738                         modal_dialogs.Add(this);
1739
1740 #if not
1741                         // Commented out; we instead let the Visible=true inside the runloop create the control
1742                         // otherwise setting DialogResult inside any of the events that are triggered by the
1743                         // create will not actually cause the form to not be displayed.
1744                         // Leaving this comment here in case there was an actual purpose to creating the control
1745                         // in here.
1746                         if (!IsHandleCreated) {
1747                                 CreateControl();
1748                         }
1749 #endif
1750
1751                         Application.RunLoop(true, new ApplicationContext(this));
1752
1753                         if (this.owner != null) {
1754                                 // Cannot use Activate(), it has a check for the current active window...
1755                                 XplatUI.Activate(this.owner.window.Handle);
1756                         }
1757                         
1758                         if (IsHandleCreated) {
1759                                 DestroyHandle ();
1760                         }
1761
1762                         if (DialogResult == DialogResult.None) {
1763                                 DialogResult = DialogResult.Cancel;
1764                         }
1765                         
1766                         return DialogResult;
1767                 }
1768
1769                 public override string ToString() {
1770                         return GetType().FullName + ", Text: " + Text;
1771                 }
1772
1773                 [Browsable (true)]
1774                 [EditorBrowsable (EditorBrowsableState.Always)]
1775                 public override bool ValidateChildren ()
1776                 {
1777                         return base.ValidateChildren ();
1778                 }
1779
1780                 [Browsable (true)]
1781                 [EditorBrowsable (EditorBrowsableState.Always)]
1782                 public override bool ValidateChildren (ValidationConstraints validationConstraints)
1783                 {
1784                         return base.ValidateChildren (validationConstraints);
1785                 }
1786                 #endregion      // Public Instance Methods
1787
1788                 #region Protected Instance Methods
1789                 protected void ActivateMdiChild(Form form) {
1790                         if (!IsMdiContainer)
1791                                 return;
1792                         mdi_container.ActivateChild (form);
1793                         OnMdiChildActivate(EventArgs.Empty);
1794                 }
1795
1796                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1797                 protected override void AdjustFormScrollbars(bool displayScrollbars) {
1798                         base.AdjustFormScrollbars (displayScrollbars);
1799                 }
1800
1801                 [EditorBrowsable(EditorBrowsableState.Never)]
1802                 [Obsolete ("This method has been deprecated")] // XXX what to use instead?
1803                 protected void ApplyAutoScaling()
1804                 {
1805                         SizeF current_size_f = GetAutoScaleSize (Font);
1806                         Size current_size = new Size ((int)Math.Round (current_size_f.Width), (int)Math.Round (current_size_f.Height));
1807                         float   dx;
1808                         float   dy;
1809
1810                         if (current_size == autoscale_base_size)
1811                                 return;
1812
1813                         if (Environment.GetEnvironmentVariable ("MONO_MWF_SCALING") == "disable"){
1814                                 return;
1815                         }
1816                         
1817                         //
1818                         // I tried applying the Fudge height factor from:
1819                         // http://blogs.msdn.com/mharsh/archive/2004/01/25/62621.aspx
1820                         // but it makes things larger without looking better.
1821                         //
1822                         if (current_size.Width != AutoScaleBaseSize.Width) {
1823                                 dx = (float)current_size.Width / AutoScaleBaseSize.Width + 0.08f;
1824                         } else {
1825                                 dx = 1;
1826                         }
1827
1828                         if (current_size.Height != AutoScaleBaseSize.Height) {
1829                                 dy = (float)current_size.Height / AutoScaleBaseSize.Height + 0.08f;
1830                         } else {
1831                                 dy = 1;
1832                         }
1833
1834                         Scale (dx, dy);
1835                         
1836                         AutoScaleBaseSize = current_size;
1837                 }
1838
1839                 protected void CenterToParent() {
1840                         Control ctl;
1841                         int     w;
1842                         int     h;
1843
1844                         // MS creates the handle here.
1845                         if (TopLevel) {
1846                                 if (!IsHandleCreated)
1847                                         CreateHandle ();
1848                         }
1849                         
1850                         if (Width > 0) {
1851                                 w = Width;
1852                         } else {
1853                                 w = DefaultSize.Width;
1854                         }
1855
1856                         if (Height > 0) {
1857                                 h = Height;
1858                         } else {
1859                                 h = DefaultSize.Height;
1860                         }
1861
1862                         ctl = null;
1863                         if (Parent != null) {
1864                                 ctl = Parent;
1865                         } else if (owner != null) {
1866                                 ctl = owner;
1867                         }
1868
1869                         if (owner != null) {
1870                                 this.Location = new Point(ctl.Left + ctl.Width / 2 - w /2, ctl.Top + ctl.Height / 2 - h / 2);
1871                         }
1872                 }
1873
1874                 protected void CenterToScreen() {
1875                         int w;
1876                         int h;
1877
1878                         // MS creates the handle here.
1879                         if (TopLevel) {
1880                                 if (!IsHandleCreated)
1881                                         CreateHandle ();
1882                         }
1883                         
1884                         if (Width > 0) {
1885                                 w = Width;
1886                         } else {
1887                                 w = DefaultSize.Width;
1888                         }
1889
1890                         if (Height > 0) {
1891                                 h = Height;
1892                         } else {
1893                                 h = DefaultSize.Height;
1894                         }
1895
1896                         Rectangle workingArea;
1897                         if (Owner == null) {
1898                                 workingArea = Screen.FromPoint (MousePosition).WorkingArea;
1899                         } else {
1900                                 workingArea = Screen.FromControl (Owner).WorkingArea;
1901                         }
1902                         this.Location = new Point (workingArea.Left + workingArea.Width / 2 - w / 2,
1903                                 workingArea.Top + workingArea.Height / 2 - h / 2);
1904                 }
1905
1906                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1907                 protected override Control.ControlCollection CreateControlsInstance() {
1908                         return base.CreateControlsInstance ();
1909                 }
1910
1911                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1912                 protected override void CreateHandle() {
1913                         base.CreateHandle ();
1914
1915                         if (!IsHandleCreated) {
1916                                 return;
1917                         }
1918                         
1919                         UpdateBounds();
1920
1921                         if ((XplatUI.SupportsTransparency() & TransparencySupport.Set) != 0) {
1922                                 if (allow_transparency) {
1923                                         XplatUI.SetWindowTransparency(Handle, opacity, TransparencyKey);
1924                                 }
1925                         }
1926
1927                         XplatUI.SetWindowMinMax(window.Handle, maximized_bounds, minimum_size, maximum_size);
1928                         
1929                         if (show_icon && (FormBorderStyle != FormBorderStyle.FixedDialog) && (icon != null)) {
1930                                 XplatUI.SetIcon(window.Handle, icon);
1931                         }
1932
1933                         if ((owner != null) && (owner.IsHandleCreated)) {
1934                                 XplatUI.SetOwner(window.Handle, owner.window.Handle);
1935                         }
1936
1937                         if (topmost) {
1938                                 XplatUI.SetTopmost(window.Handle, topmost);
1939                         }
1940
1941                         for (int i = 0; i < owned_forms.Count; i++) {
1942                                 if (owned_forms[i].IsHandleCreated)
1943                                         XplatUI.SetOwner(owned_forms[i].window.Handle, window.Handle);
1944                         }
1945                         
1946                         if (window_manager != null) {
1947                                 if (IsMdiChild && VisibleInternal) {
1948                                         MdiWindowManager wm;
1949                                         // Loop through all the other mdi siblings and raise Deactivate events.
1950                                         if (MdiParent != null) {
1951                                                 foreach (Form form in MdiParent.MdiChildren) {
1952                                                         wm = form.window_manager as MdiWindowManager;
1953                                                         if (wm != null && form != this) {
1954                                                                 // This will only raise deactivate once, and only if activate has
1955                                                                 // already been raised.
1956                                                                 wm.RaiseDeactivate ();
1957                                                         }
1958                                                 }
1959                                         }
1960                                         
1961                                         wm = window_manager as MdiWindowManager;
1962                                         wm.RaiseActivated ();
1963
1964                                         // We need to tell everyone who may have just been deactivated to redraw their titlebar
1965                                         if (MdiParent != null)
1966                                                 foreach (Form form in MdiParent.MdiChildren)
1967                                                         if (form != this && form.IsHandleCreated)
1968                                                                 XplatUI.InvalidateNC (form.Handle);
1969                                 }
1970                                 
1971                                 if (window_state != FormWindowState.Normal) {
1972                                         window_manager.SetWindowState ((FormWindowState) int.MaxValue, window_state);
1973                                 }
1974                                 XplatUI.RequestNCRecalc (window.Handle);
1975                         }
1976
1977                 }
1978
1979                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1980                 protected override void DefWndProc(ref Message m) {
1981                         base.DefWndProc (ref m);
1982                 }
1983
1984                 protected override void Dispose(bool disposing)
1985                 {
1986                         if (owned_forms != null) {
1987                                 for (int i = 0; i < owned_forms.Count; i++)
1988                                         ((Form)owned_forms[i]).Owner = null;
1989
1990                                 owned_forms.Clear ();
1991                         }
1992                         Owner = null;
1993                         base.Dispose (disposing);
1994                         
1995                         Application.RemoveForm (this);
1996                 }
1997
1998                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1999                 protected virtual void OnActivated(EventArgs e)
2000                 {
2001                         EventHandler eh = (EventHandler)(Events [ActivatedEvent]);
2002                         if (eh != null)
2003                                 eh (this, e);
2004                 }
2005
2006                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2007                 protected virtual void OnClosed(EventArgs e) {
2008                         EventHandler eh = (EventHandler)(Events [ClosedEvent]);
2009                         if (eh != null)
2010                                 eh (this, e);
2011                 }
2012
2013                 // Consider calling FireClosingEvents instead of calling this directly.
2014                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2015                 protected virtual void OnClosing(System.ComponentModel.CancelEventArgs e) {
2016                         CancelEventHandler eh = (CancelEventHandler)(Events [ClosingEvent]);
2017                         if (eh != null)
2018                                 eh (this, e);
2019                 }
2020
2021                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2022                 protected override void OnCreateControl() {
2023                         base.OnCreateControl ();
2024
2025                         if (menu != null) {
2026                                 XplatUI.SetMenu(window.Handle, menu);
2027                         }
2028
2029                         OnLoadInternal (EventArgs.Empty);
2030                         
2031                         // Send initial location
2032                         OnLocationChanged(EventArgs.Empty);
2033                 }
2034
2035                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2036                 protected virtual void OnDeactivate(EventArgs e) {
2037                         EventHandler eh = (EventHandler)(Events [DeactivateEvent]);
2038                         if (eh != null)
2039                                 eh (this, e);
2040                 }
2041
2042                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2043                 protected override void OnFontChanged(EventArgs e) {
2044                         base.OnFontChanged (e);
2045                         
2046                         if (!autoscale_base_size_set) {
2047                                 SizeF sizef = Form.GetAutoScaleSize (Font);
2048                                 autoscale_base_size = new Size ((int)Math.Round (sizef.Width), (int)Math.Round (sizef.Height));
2049                         }
2050                 }
2051
2052                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2053                 protected override void OnHandleCreated(EventArgs e) {
2054                         XplatUI.SetBorderStyle(window.Handle, form_border_style);
2055                         base.OnHandleCreated (e);
2056                 }
2057
2058                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2059                 protected override void OnHandleDestroyed(EventArgs e) {
2060                         Application.RemoveForm (this);
2061                         base.OnHandleDestroyed (e);
2062                 }
2063
2064                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2065                 protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) {
2066                         InputLanguageChangedEventHandler eh = (InputLanguageChangedEventHandler)(Events [InputLanguageChangedEvent]);
2067                         if (eh != null)
2068                                 eh (this, e);
2069                 }
2070
2071                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2072                 protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) {
2073                         InputLanguageChangingEventHandler eh = (InputLanguageChangingEventHandler)(Events [InputLanguageChangingEvent]);
2074                         if (eh != null)
2075                                 eh (this, e);
2076                 }
2077
2078                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2079                 protected virtual void OnLoad (EventArgs e){
2080                         Application.AddForm (this);
2081
2082                         EventHandler eh = (EventHandler)(Events[LoadEvent]);
2083                         if (eh != null)
2084                                 eh (this, e);
2085                 }
2086
2087                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2088                 protected virtual void OnMaximizedBoundsChanged(EventArgs e) {
2089                         EventHandler eh = (EventHandler)(Events [MaximizedBoundsChangedEvent]);
2090                         if (eh != null)
2091                                 eh (this, e);
2092                 }
2093
2094                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2095                 protected virtual void OnMaximumSizeChanged(EventArgs e) {
2096                         EventHandler eh = (EventHandler)(Events [MaximumSizeChangedEvent]);
2097                         if (eh != null)
2098                                 eh (this, e);
2099                 }
2100
2101                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2102                 protected virtual void OnMdiChildActivate(EventArgs e) {
2103                         EventHandler eh = (EventHandler)(Events [MdiChildActivateEvent]);
2104                         if (eh != null)
2105                                 eh (this, e);
2106                 }
2107
2108                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2109                 protected internal virtual void OnMenuComplete(EventArgs e) {
2110                         EventHandler eh = (EventHandler)(Events [MenuCompleteEvent]);
2111                         if (eh != null)
2112                                 eh (this, e);
2113                 }
2114
2115                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2116                 protected virtual void OnMenuStart(EventArgs e) {
2117                         EventHandler eh = (EventHandler)(Events [MenuStartEvent]);
2118                         if (eh != null)
2119                                 eh (this, e);
2120                 }
2121
2122                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2123                 protected virtual void OnMinimumSizeChanged(EventArgs e) {
2124                         EventHandler eh = (EventHandler)(Events [MinimumSizeChangedEvent]);
2125                         if (eh != null)
2126                                 eh (this, e);
2127                 }
2128
2129                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2130                 protected override void OnPaint (PaintEventArgs e) {
2131                         base.OnPaint (e);
2132
2133                         if (size_grip != null) {
2134                                 size_grip.HandlePaint (this, e);
2135                         }
2136                 }
2137
2138                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2139                 protected override void OnResize(EventArgs e) {
2140                         base.OnResize(e);
2141
2142                 }
2143
2144                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2145                 protected override void OnStyleChanged(EventArgs e) {
2146                         base.OnStyleChanged (e);
2147                 }
2148
2149                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2150                 protected override void OnTextChanged(EventArgs e) {
2151                         base.OnTextChanged (e);
2152
2153                         if (mdi_container != null)
2154                                 mdi_container.SetParentText(true);
2155                 }
2156
2157                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2158                 protected override void OnVisibleChanged(EventArgs e) {
2159                         base.OnVisibleChanged (e);
2160                         
2161                         if (Visible) {
2162                                 if (window_manager != null)
2163                                         if (WindowState == FormWindowState.Normal)
2164                                                 window_manager.SetWindowState (WindowState, WindowState);
2165                                         else
2166                                                 // We don't really have an old_state, and if we pass the same thing,
2167                                                 // it may not really change the state for us
2168                                                 window_manager.SetWindowState ((FormWindowState)(-1), WindowState);
2169                         }
2170                 }
2171
2172                 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
2173                         if (base.ProcessCmdKey (ref msg, keyData)) {
2174                                 return true;
2175                         }
2176
2177                         // Handle keyboard cues state.
2178                         if ((keyData & Keys.Alt) != 0) {
2179                                 Control toplevel = TopLevelControl;
2180                                 if (toplevel != null) {
2181                                         IntPtr param = MakeParam ((int) MsgUIState.UIS_CLEAR, (int) MsgUIState.UISF_HIDEACCEL);
2182                                         XplatUI.SendMessage (toplevel.Handle, Msg.WM_CHANGEUISTATE, param, IntPtr.Zero);
2183                                 }
2184                         }
2185
2186                         // Give our menu a shot
2187                         if (ActiveMenu != null) {
2188                                 if (ActiveMenu.ProcessCmdKey (ref msg, keyData))
2189                                         return true;
2190                         }
2191
2192                         // Detect any active ContextMenu for a child control that
2193                         // can't receive focus (which means: both input and preprocess)
2194                         if (ActiveTracker != null && ActiveTracker.TopMenu is ContextMenu) {
2195                                 ContextMenu cmenu = ActiveTracker.TopMenu as ContextMenu;
2196                                 if (cmenu.SourceControl != this && cmenu.ProcessCmdKey (ref msg, keyData))
2197                                         return true;
2198                         }
2199
2200                         if (IsMdiChild) {
2201                                 switch (keyData)
2202                                 {
2203                                 case Keys.Control | Keys.F4:
2204                                 case Keys.Control | Keys.Shift | Keys.F4:
2205                                         Close ();
2206                                         return true;
2207                                 case Keys.Control | Keys.Tab:
2208                                 case Keys.Control | Keys.F6:
2209                                         MdiParent.MdiContainer.ActivateNextChild ();
2210                                         return true;
2211                                 case Keys.Control | Keys.Shift | Keys.Tab:
2212                                 case Keys.Control | Keys.Shift | Keys.F6:
2213                                         MdiParent.MdiContainer.ActivatePreviousChild ();
2214                                         return true;
2215                                 case Keys.Alt | Keys.OemMinus:
2216                                 case Keys.Alt | Keys.Subtract:
2217                                         (this.WindowManager as MdiWindowManager).ShowPopup (Point.Empty);
2218                                         return true;
2219                                 }
2220                         }
2221
2222                         return false;
2223                 }
2224
2225                 // LAMESPEC - Not documented that Form overrides ProcessDialogChar; class-status showed
2226                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2227                 protected override bool ProcessDialogChar(char charCode) {
2228                         return base.ProcessDialogChar (charCode);
2229                 }
2230
2231                 protected override bool ProcessDialogKey(Keys keyData) {
2232                         if ((keyData & Keys.Modifiers) == 0) {
2233                                 if (keyData == Keys.Enter) {
2234                                         IntPtr window = XplatUI.GetFocus ();
2235                                         Control c = Control.FromHandle (window);
2236                                         if (c is Button && c.FindForm () == this) {
2237                                                 ((Button)c).PerformClick ();
2238                                                 return true;
2239                                         }
2240                                         else if (accept_button != null) {
2241                                                 // Set ActiveControl to force any Validation to take place.
2242                                                 ActiveControl = (accept_button as Control);
2243                                                 if (ActiveControl == accept_button) // else Validation failed
2244                                                         accept_button.PerformClick();
2245                                                 return true;
2246                                         }
2247                                 } else if (keyData == Keys.Escape && cancel_button != null) {
2248                                         cancel_button.PerformClick();
2249                                         return true;
2250                                 }
2251                         }
2252                         return base.ProcessDialogKey(keyData);
2253                 }
2254
2255                 protected override bool ProcessKeyPreview(ref Message m) {
2256                         if (key_preview) {
2257                                 if (ProcessKeyEventArgs(ref m)) {
2258                                         return true;
2259                                 }
2260                         }
2261                         return base.ProcessKeyPreview (ref m);
2262                 }
2263
2264                 protected override bool ProcessTabKey(bool forward) {
2265                         bool need_refresh = !show_focus_cues;
2266                         show_focus_cues = true;
2267                         
2268                         bool control_activated = SelectNextControl(ActiveControl, forward, true, true, true);
2269                         
2270                         if (need_refresh && ActiveControl != null)
2271                                 ActiveControl.Invalidate ();
2272                                 
2273                         return control_activated;
2274                 }
2275
2276                 [EditorBrowsable (EditorBrowsableState.Never)]
2277                 protected override void ScaleCore (float x, float y)
2278                 {
2279                         base.ScaleCore (x, y);
2280                 }
2281
2282                 protected override void Select(bool directed, bool forward) {
2283                         Form    parent;
2284
2285
2286                         // MS causes the handle to be created here.
2287                         if (!IsHandleCreated)
2288                                 if (!IsHandleCreated)
2289                                         CreateHandle ();
2290                         
2291                         if (directed) {
2292                                 base.SelectNextControl(null, forward, true, true, true);
2293                         }
2294
2295                         parent = this.ParentForm;
2296                         if (parent != null) {
2297                                 parent.ActiveControl = this;
2298                         }
2299
2300                         Activate();
2301                 }
2302
2303                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2304                 protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
2305                         Size min_size;
2306                         
2307                         if (WindowState == FormWindowState.Minimized)
2308                                 min_size = SystemInformation.MinimizedWindowSize;
2309                         else
2310                                 switch (FormBorderStyle) {
2311                                         case FormBorderStyle.None:
2312                                                 min_size = XplatUI.MinimumNoBorderWindowSize;
2313                                                 break;
2314                                         case FormBorderStyle.FixedToolWindow:
2315                                                 min_size = XplatUI.MinimumFixedToolWindowSize;
2316                                                 break;
2317                                         case FormBorderStyle.SizableToolWindow:
2318                                                 min_size = XplatUI.MinimumSizeableToolWindowSize;
2319                                                 break;
2320                                         default:
2321                                                 min_size = SystemInformation.MinimumWindowSize;
2322                                                 break;
2323                                 }
2324                         
2325                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width)
2326                                 width = Math.Max (width, min_size.Width);
2327                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height)
2328                                 height = Math.Max (height, min_size.Height);
2329                                 
2330                         base.SetBoundsCore (x, y, width, height, specified);
2331
2332                         int restore_x = (specified & BoundsSpecified.X) == BoundsSpecified.X ? x : restore_bounds.X;
2333                         int restore_y = (specified & BoundsSpecified.Y) == BoundsSpecified.Y ? y : restore_bounds.Y;
2334                         int restore_w = (specified & BoundsSpecified.Width) == BoundsSpecified.Width ? width : restore_bounds.Width;
2335                         int restore_h = (specified & BoundsSpecified.Height) == BoundsSpecified.Height ? height : restore_bounds.Height;
2336                         restore_bounds = new Rectangle (restore_x, restore_y, restore_w, restore_h);
2337                 }
2338
2339                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2340                 protected override void SetClientSizeCore(int x, int y) {
2341                         if ((minimum_size.Width != 0) && (x < minimum_size.Width)) {
2342                                 x = minimum_size.Width;
2343                         } else if ((maximum_size.Width != 0) && (x > maximum_size.Width)) {
2344                                 x = maximum_size.Width;
2345                         }
2346
2347                         if ((minimum_size.Height != 0) && (y < minimum_size.Height)) {
2348                                 y = minimum_size.Height;
2349                         } else if ((maximum_size.Height != 0) && (y > maximum_size.Height)) {
2350                                 y = maximum_size.Height;
2351                         }
2352
2353                         Rectangle ClientRect = new Rectangle(0, 0, x, y);
2354                         Rectangle WindowRect;
2355                         CreateParams cp = this.CreateParams;
2356
2357                         clientsize_set = new Size(x, y);
2358
2359                         if (XplatUI.CalculateWindowRect(ref ClientRect, cp, cp.menu, out WindowRect)) {
2360                                 SetBounds(bounds.X, bounds.Y, WindowRect.Width, WindowRect.Height, BoundsSpecified.Size);
2361                         }
2362                 }
2363
2364                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2365                 protected override void SetVisibleCore(bool value)
2366                 {
2367                         if (value)
2368                                 close_raised = false;
2369
2370                         if (IsMdiChild && !MdiParent.Visible) {
2371                                 if (value != Visible) {
2372                                         MdiWindowManager wm = (MdiWindowManager) window_manager;
2373                                         wm.IsVisiblePending = value;
2374                                         OnVisibleChanged (EventArgs.Empty);
2375                                         return;
2376                                 }
2377                         } else {
2378                                 is_changing_visible_state++;
2379                                 has_been_visible = value || has_been_visible;
2380                                 base.SetVisibleCore (value);
2381                                 if (value) {
2382                                         Application.AddForm (this);
2383                                 }
2384                                 
2385                                 if (value && WindowState != FormWindowState.Normal)
2386                                         XplatUI.SendMessage (Handle, Msg.WM_SHOWWINDOW, (IntPtr)1, IntPtr.Zero);
2387                                         
2388                                 is_changing_visible_state--;
2389                         }
2390                         
2391                         if (value && IsMdiContainer) {
2392                                 Form [] children = MdiChildren;
2393                                 for (int i = 0; i < children.Length; i++) {
2394                                         Form child = children [i];
2395                                         MdiWindowManager wm = (MdiWindowManager) child.window_manager;
2396                                         if (!child.IsHandleCreated && wm.IsVisiblePending) {
2397                                                 wm.IsVisiblePending = false;
2398                                                 child.Visible = true;
2399                                         }
2400                                 }
2401                         }
2402                         
2403                         if (value && IsMdiChild){
2404                                 PerformLayout ();
2405                                 ThemeEngine.Current.ManagedWindowSetButtonLocations (window_manager);
2406                         }
2407                         
2408                         // Shown event is only called once, the first time the form is made visible
2409                         if (value && !shown_raised) {
2410                                 this.OnShown (EventArgs.Empty);
2411                                 shown_raised = true;
2412                         }
2413                         
2414                         if (value && !IsMdiChild) {
2415                                 if (ActiveControl == null)
2416                                         SelectNextControl (null, true, true, true, false);
2417                                 if (ActiveControl != null)
2418                                         SendControlFocus (ActiveControl);
2419                                 else
2420                                         this.Focus ();
2421                         }
2422                 }
2423
2424                 protected override void UpdateDefaultButton() {
2425                         base.UpdateDefaultButton ();
2426                 }
2427
2428                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2429                 protected override void WndProc(ref Message m) {
2430 #if debug
2431                         Console.WriteLine(DateTime.Now.ToLongTimeString () + " Form {0} ({2}) received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), m.ToString (), Text);
2432 #endif
2433
2434                         if (window_manager != null && window_manager.WndProc (ref m)) {
2435                                 return;
2436                         }
2437
2438                         switch ((Msg)m.Msg) {
2439                         case Msg.WM_DESTROY: {
2440                                 WmDestroy (ref m);
2441                                 return;
2442                         }
2443
2444                         case Msg.WM_CLOSE: {
2445                                 WmClose (ref m);
2446                                 return;
2447                         }
2448
2449                         case Msg.WM_WINDOWPOSCHANGED: {
2450                                 WmWindowPosChanged (ref m);
2451                                 return;
2452                         }
2453
2454                         case Msg.WM_SYSCOMMAND: {
2455                                 WmSysCommand (ref m);
2456                                 break;
2457                         }
2458
2459                         case Msg.WM_ACTIVATE: {
2460                                 WmActivate (ref m);
2461                                 return;
2462                         }
2463
2464                         case Msg.WM_KILLFOCUS: {
2465                                 WmKillFocus (ref m);
2466                                 return;
2467                         }
2468
2469                         case Msg.WM_SETFOCUS: {
2470                                 WmSetFocus (ref m);
2471                                 return;
2472                         }
2473
2474                         // Menu drawing
2475                         case Msg.WM_NCHITTEST: {
2476                                 WmNcHitTest (ref m);
2477                                 return;
2478                         }
2479
2480                         case Msg.WM_NCLBUTTONDOWN: {
2481                                 WmNcLButtonDown (ref m);
2482                                 return;
2483                         }
2484
2485                         case Msg.WM_NCLBUTTONUP: {
2486                                 WmNcLButtonUp (ref m);
2487                                 return;
2488                         }
2489
2490                         case Msg.WM_NCMOUSELEAVE: {
2491                                 WmNcMouseLeave (ref m);
2492                                 return;
2493                         }
2494
2495                         case Msg.WM_NCMOUSEMOVE: {
2496                                 WmNcMouseMove (ref m);
2497                                 return;
2498                         }
2499
2500                         case Msg.WM_NCPAINT: {
2501                                 WmNcPaint (ref m);
2502                                 return;
2503                         }
2504
2505                         case Msg.WM_NCCALCSIZE: {
2506                                 WmNcCalcSize (ref m);
2507                                 break;
2508                         }
2509
2510                         case Msg.WM_GETMINMAXINFO: {
2511                                 WmGetMinMaxInfo (ref m);
2512                                 break;
2513                         }
2514                         
2515                         case Msg.WM_ENTERSIZEMOVE: {
2516                                 OnResizeBegin (EventArgs.Empty);
2517                                 break;
2518                         }
2519                         
2520                         case Msg.WM_EXITSIZEMOVE: {
2521                                 OnResizeEnd (EventArgs.Empty);
2522                                 break;
2523                         }
2524
2525                         default: {
2526                                 base.WndProc (ref m);
2527                                 break;
2528                         }
2529                         }
2530                 }
2531                 #endregion      // Protected Instance Methods
2532
2533 #region WM methods
2534
2535                 private void WmDestroy (ref Message m)
2536                 {
2537                         if (!RecreatingHandle)
2538                                 this.closing = true;
2539
2540                         base.WndProc (ref m);
2541                 }
2542                 
2543                 internal bool RaiseCloseEvents (bool last_check, bool cancel)
2544                 {
2545                         if (last_check && Visible) {
2546                                 Hide ();
2547                         }
2548                         
2549                         if (close_raised || (last_check && closed)) {
2550                                 return false;
2551                         }
2552                         
2553                         close_raised = true;
2554                         bool cancelled = FireClosingEvents (CloseReason.UserClosing, cancel);
2555                         if (!cancelled) {
2556                                 if (!last_check || DialogResult != DialogResult.None) {
2557                                         if (mdi_container != null)
2558                                                 foreach (Form mdi_child in mdi_container.MdiChildren)
2559                                                         mdi_child.FireClosedEvents (CloseReason.UserClosing);
2560
2561                                         FireClosedEvents (CloseReason.UserClosing);
2562                                 }
2563                                 closing = true;
2564                                 shown_raised = false;
2565                         } else {
2566                                 DialogResult = DialogResult.None;
2567                                 closing = false;
2568                                 close_raised = false;
2569                         }
2570                                 
2571                         return cancelled;
2572                 }
2573
2574                 private void WmClose (ref Message m)
2575                 {
2576                         if (this.Enabled == false)
2577                                 return; // prevent closing a disabled form.
2578
2579                         Form act = Form.ActiveForm;
2580                         // Don't close this form if there's another modal form visible.
2581                         if (act != null && act != this && act.Modal == true) {
2582                                 // Check if any of the parents up the tree is the modal form, 
2583                                 // in which case we can still close this form.
2584                                 Control current = this;
2585                                 while (current != null && current.Parent != act) {
2586                                         current = current.Parent;
2587                                 }
2588                                 if (current == null || current.Parent != act) {
2589                                         return;
2590                                 }
2591                         }
2592
2593                         bool mdi_cancel = false;
2594                         
2595                         // Give any MDI children the opportunity to cancel the close
2596                         if (mdi_container != null)
2597                                 foreach (Form mdi_child in mdi_container.MdiChildren)
2598                                         mdi_cancel = mdi_child.FireClosingEvents (CloseReason.MdiFormClosing, mdi_cancel);
2599
2600                         bool validate_cancel = false;
2601                         if (!suppress_closing_events)
2602                                 validate_cancel = !ValidateChildren ();
2603
2604                         if (suppress_closing_events || 
2605                             !RaiseCloseEvents (false, validate_cancel || mdi_cancel)) {
2606                                 if (is_modal) {
2607                                         Hide ();
2608                                 } else {
2609                                         Dispose ();                                     
2610                                         if (act != null && act != this)
2611                                                 act.SelectActiveControl ();
2612                                 }
2613                                 mdi_parent = null;
2614                         } else {
2615                                 if (is_modal) {
2616                                         DialogResult = DialogResult.None;
2617                                 }
2618                                 closing = false;        
2619                         }
2620                 }
2621                 
2622                 private void WmWindowPosChanged (ref Message m)
2623                 {
2624                         // When a form is minimized/restored:
2625                         // * Win32: X and Y are set to negative values/restored, 
2626                         //   size remains the same.
2627                         // * X11: Location and Size remain the same.
2628                         // 
2629                         // In both cases we have to fire Resize explicitly here, 
2630                         // because of the unmodified Size due to which Control
2631                         // doesn't fire it.
2632                         // 
2633                         if (window_state != FormWindowState.Minimized && WindowState != FormWindowState.Minimized)
2634                                 base.WndProc (ref m);
2635                         else { // minimized or restored
2636                                 if (!is_minimizing) {
2637                                         // Avoid recursive calls here as code in OnSizeChanged might 
2638                                         // cause a WM_WINDOWPOSCHANGED to be sent.
2639                                         is_minimizing = true;
2640                                         OnSizeChanged (EventArgs.Empty);
2641                                         is_minimizing = false;
2642                                 }
2643                         }
2644
2645                         if (WindowState == FormWindowState.Normal)
2646                                 restore_bounds = Bounds;
2647                 }
2648
2649                 private void WmSysCommand (ref Message m)
2650                 {
2651                         // Let *Strips know the app's title bar was clicked
2652                         if (XplatUI.IsEnabled (Handle))
2653                                 ToolStripManager.FireAppClicked ();
2654
2655                         base.WndProc (ref m);
2656                 }
2657
2658                 private void WmActivate (ref Message m)
2659                 {
2660                         if (!this.Enabled && modal_dialogs.Count > 0)
2661                         {
2662                                 (modal_dialogs[modal_dialogs.Count -1] as Form).Activate ();
2663                                 return; // prevent Activating of disabled form.
2664                         }
2665
2666                         if (m.WParam != (IntPtr)WindowActiveFlags.WA_INACTIVE) {
2667                                 if (is_loaded) {
2668                                         SelectActiveControl ();
2669
2670                                         if (ActiveControl != null && !ActiveControl.Focused)
2671                                                 SendControlFocus (ActiveControl);
2672                                 }
2673
2674                                 IsActive = true;
2675                         } else {
2676                                 if (XplatUI.IsEnabled (Handle) && XplatUI.GetParent (m.LParam) != Handle)
2677                                         ToolStripManager.FireAppFocusChanged (this);
2678                                 IsActive = false;
2679                         }
2680                 }
2681                 
2682                 private void WmKillFocus (ref Message m)
2683                 {
2684                         base.WndProc (ref m);
2685                 }
2686                 
2687                 private void WmSetFocus (ref Message m)
2688                 {
2689                         if (ActiveControl != null && ActiveControl != this) {
2690                                 ActiveControl.Focus ();
2691                                 return; // FIXME - do we need to run base.WndProc, even though we just changed focus?
2692                         }
2693                         if (IsMdiContainer) {
2694                                 mdi_container.SendFocusToActiveChild ();
2695                                 return;
2696                         }
2697                         base.WndProc (ref m);
2698                 }
2699                 
2700                 private void WmNcHitTest (ref Message m)
2701                 {
2702                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2703                                 int x = LowOrder ((int)m.LParam.ToInt32 ());
2704                                 int y = HighOrder ((int)m.LParam.ToInt32 ());
2705
2706                                 XplatUI.ScreenToMenu (ActiveMenu.Wnd.window.Handle, ref x, ref y);
2707
2708                                 // If point is under menu return HTMENU, it prevents Win32 to return HTMOVE.
2709                                 if ((x > 0) && (y > 0) && (x < ActiveMenu.Rect.Width) && (y < ActiveMenu.Rect.Height)) {
2710                                         m.Result = new IntPtr ((int)HitTest.HTMENU);
2711                                         return;
2712                                 }
2713                         }
2714
2715                         base.WndProc (ref m);
2716                 }
2717                 
2718                 private void WmNcLButtonDown (ref Message m)
2719                 {
2720                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2721                                 ActiveMenu.OnMouseDown (this, new MouseEventArgs (FromParamToMouseButtons ((int)m.WParam.ToInt32 ()), mouse_clicks, Control.MousePosition.X, Control.MousePosition.Y, 0));
2722                         }
2723
2724                         if (ActiveMaximizedMdiChild != null && ActiveMenu != null) {
2725                                 if (ActiveMaximizedMdiChild.HandleMenuMouseDown (ActiveMenu,
2726                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2727                                                 HighOrder ((int)m.LParam.ToInt32 ()))) {
2728                                         // Don't let base process this message, otherwise we won't
2729                                         // get a WM_NCLBUTTONUP.
2730                                         return;
2731                                 }
2732                         }
2733                         base.WndProc (ref m);
2734                 }
2735                 
2736                 private void WmNcLButtonUp (ref Message m)
2737                 {
2738                         if (ActiveMaximizedMdiChild != null && ActiveMenu != null) {
2739                                 ActiveMaximizedMdiChild.HandleMenuMouseUp (ActiveMenu,
2740                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2741                                                 HighOrder ((int)m.LParam.ToInt32 ()));
2742                         }
2743                         base.WndProc (ref m);
2744                 }
2745                 
2746                 private void WmNcMouseLeave (ref Message m)
2747                 {
2748                         if (ActiveMaximizedMdiChild != null && ActiveMenu != null) {
2749                                 ActiveMaximizedMdiChild.HandleMenuMouseLeave (ActiveMenu,
2750                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2751                                                 HighOrder ((int)m.LParam.ToInt32 ()));
2752                         }
2753                         base.WndProc (ref m);
2754                 }
2755                 
2756                 private void WmNcMouseMove (ref Message m)
2757                 {
2758                         if (XplatUI.IsEnabled (Handle) && ActiveMenu != null) {
2759                                 ActiveMenu.OnMouseMove (this, new MouseEventArgs (FromParamToMouseButtons ((int)m.WParam.ToInt32 ()), mouse_clicks, LowOrder ((int)m.LParam.ToInt32 ()), HighOrder ((int)m.LParam.ToInt32 ()), 0));
2760                         }
2761
2762                         if (ActiveMaximizedMdiChild != null && ActiveMenu != null) {
2763                                 XplatUI.RequestAdditionalWM_NCMessages (Handle, false, true);
2764                                 ActiveMaximizedMdiChild.HandleMenuMouseMove (ActiveMenu,
2765                                                 LowOrder ((int)m.LParam.ToInt32 ()),
2766                                                 HighOrder ((int)m.LParam.ToInt32 ()));
2767                         }
2768                         base.WndProc (ref m);
2769                 }
2770                 
2771                 private void WmNcPaint (ref Message m)
2772                 {
2773                         if (ActiveMenu != null) {
2774                                 PaintEventArgs pe = XplatUI.PaintEventStart (ref m, Handle, false);
2775                                 Point pnt = XplatUI.GetMenuOrigin (window.Handle);
2776
2777                                 // The entire menu has to be in the clip rectangle because the 
2778                                 // control buttons are right-aligned and otherwise they would
2779                                 // stay painted when the window gets resized.
2780                                 Rectangle clip = new Rectangle (pnt.X, pnt.Y, ClientSize.Width, 0);
2781                                 clip = Rectangle.Union (clip, pe.ClipRectangle);
2782                                 pe.SetClip (clip);
2783                                 pe.Graphics.SetClip (clip);
2784
2785                                 ActiveMenu.Draw (pe, new Rectangle (pnt.X, pnt.Y, ClientSize.Width, 0));
2786
2787                                 if (ActiveMaximizedMdiChild != null)
2788                                         ActiveMaximizedMdiChild.DrawMaximizedButtons (ActiveMenu, pe);
2789
2790                                 XplatUI.PaintEventEnd (ref m, Handle, false);
2791                         }
2792
2793                         base.WndProc (ref m);
2794                 }
2795                 
2796                 private void WmNcCalcSize (ref Message m)
2797                 {
2798                         XplatUIWin32.NCCALCSIZE_PARAMS ncp;
2799
2800                         if ((ActiveMenu != null) && (m.WParam == (IntPtr)1)) {
2801                                 ncp = (XplatUIWin32.NCCALCSIZE_PARAMS)Marshal.PtrToStructure (m.LParam, typeof (XplatUIWin32.NCCALCSIZE_PARAMS));
2802
2803                                 // Adjust for menu
2804                                 ncp.rgrc1.top += ThemeEngine.Current.CalcMenuBarSize (DeviceContext, ActiveMenu, ClientSize.Width);
2805                                 Marshal.StructureToPtr (ncp, m.LParam, true);
2806                         }
2807                         DefWndProc (ref m);             
2808                 }
2809                 
2810                 private void WmGetMinMaxInfo (ref Message m)
2811                 {
2812                         MINMAXINFO mmi;
2813
2814                         if (m.LParam != IntPtr.Zero) {
2815                                 mmi = (MINMAXINFO)Marshal.PtrToStructure (m.LParam, typeof (MINMAXINFO));
2816
2817                                 default_maximized_bounds = new Rectangle (mmi.ptMaxPosition.x, mmi.ptMaxPosition.y, mmi.ptMaxSize.x, mmi.ptMaxSize.y);
2818                                 if (maximized_bounds != Rectangle.Empty) {
2819                                         mmi.ptMaxPosition.x = maximized_bounds.Left;
2820                                         mmi.ptMaxPosition.y = maximized_bounds.Top;
2821                                         mmi.ptMaxSize.x = maximized_bounds.Width;
2822                                         mmi.ptMaxSize.y = maximized_bounds.Height;
2823                                 }
2824
2825                                 if (minimum_size != Size.Empty) {
2826                                         mmi.ptMinTrackSize.x = minimum_size.Width;
2827                                         mmi.ptMinTrackSize.y = minimum_size.Height;
2828                                 }
2829
2830                                 if (maximum_size != Size.Empty) {
2831                                         mmi.ptMaxTrackSize.x = maximum_size.Width;
2832                                         mmi.ptMaxTrackSize.y = maximum_size.Height;
2833                                 }
2834                                 Marshal.StructureToPtr (mmi, m.LParam, false);
2835                         }
2836                 }
2837 #endregion
2838
2839                 #region Internal / Private Methods
2840                 internal void ActivateFocusCues ()
2841                 {
2842                         bool need_refresh = !show_focus_cues;
2843                         show_focus_cues = true;
2844                         
2845                         if (need_refresh)
2846                                 ActiveControl.Invalidate ();
2847                 }
2848                 
2849                 internal override void FireEnter ()
2850                 {
2851                         // do nothing - forms don't generate OnEnter
2852                 }
2853
2854                 internal override void FireLeave ()
2855                 {
2856                         // do nothing - forms don't generate OnLeave
2857                 }
2858
2859                 internal void RemoveWindowManager ()
2860                 {
2861                         window_manager = null;
2862                 }
2863                 
2864                 internal override void CheckAcceptButton ()
2865                 {
2866                         if (accept_button != null) {
2867                                 Button a_button = accept_button as Button;
2868
2869                                 if (ActiveControl == a_button)
2870                                         return;
2871                                 
2872                                 // If the accept_button isn't a Button, we don't need to do
2873                                 // the rest of this.
2874                                 if (a_button == null)
2875                                         return;
2876                                         
2877                                 if (ActiveControl is Button)
2878                                         a_button.paint_as_acceptbutton = false;
2879                                 else
2880                                         a_button.paint_as_acceptbutton = true;
2881                                         
2882                                 a_button.Invalidate ();
2883                         }
2884                 }
2885
2886                 internal override bool ActivateOnShow { get { return !this.ShowWithoutActivation; } }
2887                 
2888                 private void OnLoadInternal (EventArgs e)
2889                 {
2890                         if (AutoScale) {
2891                                 ApplyAutoScaling ();
2892                                 AutoScale = false;
2893                         }
2894
2895                         if (!IsDisposed) {
2896                                 OnSizeInitializedOrChanged ();
2897                                 
2898                                 // We do this here because when we load the MainForm,
2899                                 // it happens before the exception catcher in NativeWindow,
2900                                 // so the user can error in handling Load and we wouldn't catch it.
2901                                 try {
2902                                         OnLoad (e);
2903                                 }
2904                                 catch (Exception ex) {
2905                                         Application.OnThreadException (ex);
2906                                 }
2907
2908                                 if (!IsDisposed)
2909                                         is_visible = true;
2910                         }
2911                         
2912                         if (!IsMdiChild && !IsDisposed) {
2913                                 switch (StartPosition) {
2914                                         case FormStartPosition.CenterScreen:
2915                                                 this.CenterToScreen ();
2916                                                 break;
2917                                         case FormStartPosition.CenterParent:
2918                                                 this.CenterToParent ();
2919                                                 break;
2920                                         case FormStartPosition.Manual:
2921                                                 Left = CreateParams.X;
2922                                                 Top = CreateParams.Y;
2923                                                 break;
2924                                 }
2925                         }
2926                         
2927                         is_loaded = true;
2928                 }
2929                 #endregion
2930                 
2931                 #region Events
2932                 static object ActivatedEvent = new object ();
2933                 static object ClosedEvent = new object ();
2934                 static object ClosingEvent = new object ();
2935                 static object DeactivateEvent = new object ();
2936                 static object InputLanguageChangedEvent = new object ();
2937                 static object InputLanguageChangingEvent = new object ();
2938                 static object LoadEvent = new object ();
2939                 static object MaximizedBoundsChangedEvent = new object ();
2940                 static object MaximumSizeChangedEvent = new object ();
2941                 static object MdiChildActivateEvent = new object ();
2942                 static object MenuCompleteEvent = new object ();
2943                 static object MenuStartEvent = new object ();
2944                 static object MinimumSizeChangedEvent = new object ();
2945
2946                 public event EventHandler Activated {
2947                         add { Events.AddHandler (ActivatedEvent, value); }
2948                         remove { Events.RemoveHandler (ActivatedEvent, value); }
2949                 }
2950
2951                 [Browsable (false)]
2952                 [EditorBrowsable (EditorBrowsableState.Never)]
2953                 public event EventHandler Closed {
2954                         add { Events.AddHandler (ClosedEvent, value); }
2955                         remove { Events.RemoveHandler (ClosedEvent, value); }
2956                 }
2957
2958                 [Browsable (false)]
2959                 [EditorBrowsable (EditorBrowsableState.Never)]
2960                 public event CancelEventHandler Closing {
2961                         add { Events.AddHandler (ClosingEvent, value); }
2962                         remove { Events.RemoveHandler (ClosingEvent, value); }
2963                 }
2964
2965                 public event EventHandler Deactivate {
2966                         add { Events.AddHandler (DeactivateEvent, value); }
2967                         remove { Events.RemoveHandler (DeactivateEvent, value); }
2968                 }
2969
2970                 public event InputLanguageChangedEventHandler InputLanguageChanged {
2971                         add { Events.AddHandler (InputLanguageChangedEvent, value); }
2972                         remove { Events.RemoveHandler (InputLanguageChangedEvent, value); }
2973                 }
2974
2975                 public event InputLanguageChangingEventHandler InputLanguageChanging {
2976                         add { Events.AddHandler (InputLanguageChangingEvent, value); }
2977                         remove { Events.RemoveHandler (InputLanguageChangingEvent, value); }
2978                 }
2979
2980                 public event EventHandler Load {
2981                         add { Events.AddHandler (LoadEvent, value); }
2982                         remove { Events.RemoveHandler (LoadEvent, value); }
2983                 }
2984
2985                 public event EventHandler MaximizedBoundsChanged {
2986                         add { Events.AddHandler (MaximizedBoundsChangedEvent, value); }
2987                         remove { Events.RemoveHandler (MaximizedBoundsChangedEvent, value); }
2988                 }
2989
2990                 public event EventHandler MaximumSizeChanged {
2991                         add { Events.AddHandler (MaximumSizeChangedEvent, value); }
2992                         remove { Events.RemoveHandler (MaximumSizeChangedEvent, value); }
2993                 }
2994
2995                 public event EventHandler MdiChildActivate {
2996                         add { Events.AddHandler (MdiChildActivateEvent, value); }
2997                         remove { Events.RemoveHandler (MdiChildActivateEvent, value); }
2998                 }
2999
3000                 [Browsable (false)]
3001                 public event EventHandler MenuComplete {
3002                         add { Events.AddHandler (MenuCompleteEvent, value); }
3003                         remove { Events.RemoveHandler (MenuCompleteEvent, value); }
3004                 }
3005
3006                 [Browsable (false)]
3007                 public event EventHandler MenuStart {
3008                         add { Events.AddHandler (MenuStartEvent, value); }
3009                         remove { Events.RemoveHandler (MenuStartEvent, value); }
3010                 }
3011
3012                 public event EventHandler MinimumSizeChanged {
3013                         add { Events.AddHandler (MinimumSizeChangedEvent, value); }
3014                         remove { Events.RemoveHandler (MinimumSizeChangedEvent, value); }
3015                 }
3016
3017
3018                 [Browsable(false)]
3019                 [EditorBrowsable(EditorBrowsableState.Never)]
3020                 public new event EventHandler TabIndexChanged {
3021                         add { base.TabIndexChanged += value; }
3022                         remove { base.TabIndexChanged -= value; }
3023                 }
3024
3025                 [SettingsBindable (true)]
3026                 public override string Text {
3027                         get {
3028                                 return base.Text;
3029                         }
3030
3031                         set {
3032                                 base.Text = value;
3033                         }
3034                 }
3035
3036                 [SettingsBindable (true)]
3037                 public new Point Location {
3038                         get {
3039                                 return base.Location;
3040                         }
3041
3042                         set {
3043                                 base.Location = value;
3044                         }
3045                 }
3046
3047                 static object FormClosingEvent = new object ();
3048                 static object FormClosedEvent = new object ();
3049                 static object HelpButtonClickedEvent = new object ();
3050                 static object ResizeEndEvent = new object ();
3051                 static object ResizeBeginEvent = new object ();
3052                 static object RightToLeftLayoutChangedEvent = new object ();
3053                 static object ShownEvent = new object ();
3054
3055                 [Browsable (true)]
3056                 [EditorBrowsable (EditorBrowsableState.Always)]
3057                 public new event EventHandler AutoSizeChanged {
3058                         add { base.AutoSizeChanged += value; }
3059                         remove { base.AutoSizeChanged -= value; }
3060                 }
3061
3062                 [Browsable (true)]
3063                 [EditorBrowsable (EditorBrowsableState.Always)]
3064                 public new event EventHandler AutoValidateChanged {
3065                         add { base.AutoValidateChanged += value; }
3066                         remove { base.AutoValidateChanged -= value; }
3067                 }
3068
3069                 public event FormClosingEventHandler FormClosing {
3070                         add { Events.AddHandler (FormClosingEvent, value); }
3071                         remove { Events.RemoveHandler (FormClosingEvent, value); }
3072                 }
3073
3074                 public event FormClosedEventHandler FormClosed {
3075                         add { Events.AddHandler (FormClosedEvent, value); }
3076                         remove { Events.RemoveHandler (FormClosedEvent, value); }
3077                 }
3078
3079                 [Browsable (true)]
3080                 [EditorBrowsable (EditorBrowsableState.Always)]
3081                 public event CancelEventHandler HelpButtonClicked {
3082                         add { Events.AddHandler (HelpButtonClickedEvent, value); }
3083                         remove { Events.RemoveHandler (HelpButtonClickedEvent, value); }
3084                 }
3085
3086                 [Browsable (false)]
3087                 [EditorBrowsable (EditorBrowsableState.Never)]
3088                 public new event EventHandler MarginChanged {
3089                         add { base.MarginChanged += value; }
3090                         remove { base.MarginChanged -= value; }
3091                 }
3092
3093                 public event EventHandler RightToLeftLayoutChanged {
3094                         add { Events.AddHandler (RightToLeftLayoutChangedEvent, value); }
3095                         remove { Events.RemoveHandler (RightToLeftLayoutChangedEvent, value); }
3096                 }
3097
3098                 public event EventHandler ResizeBegin {
3099                         add { Events.AddHandler (ResizeBeginEvent, value); }
3100                         remove { Events.RemoveHandler (ResizeBeginEvent, value); }
3101                 }
3102
3103                 public event EventHandler ResizeEnd {
3104                         add { Events.AddHandler (ResizeEndEvent, value); }
3105                         remove { Events.RemoveHandler (ResizeEndEvent, value); }
3106                 }
3107
3108                 public event EventHandler Shown {
3109                         add { Events.AddHandler (ShownEvent, value); }
3110                         remove { Events.RemoveHandler (ShownEvent, value); }
3111                 }
3112
3113                 [Browsable (false)]
3114                 [EditorBrowsable (EditorBrowsableState.Never)]
3115                 public new event EventHandler TabStopChanged {
3116                         add { base.TabStopChanged += value; }
3117                         remove { base.TabStopChanged -= value; }
3118                 }
3119
3120                 protected override void OnBackgroundImageChanged (EventArgs e)
3121                 {
3122                         base.OnBackgroundImageChanged (e);
3123                 }
3124
3125                 protected override void OnBackgroundImageLayoutChanged (EventArgs e)
3126                 {
3127                         base.OnBackgroundImageLayoutChanged (e);
3128                 }
3129
3130                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3131                 protected override void OnEnabledChanged (EventArgs e)
3132                 {
3133                         base.OnEnabledChanged (e);
3134                 }
3135
3136                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3137                 protected override void OnEnter (EventArgs e)
3138                 {
3139                         base.OnEnter (e);
3140                 }
3141
3142                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3143                 protected virtual void OnFormClosed (FormClosedEventArgs e) {
3144                         Application.RemoveForm (this);
3145                         FormClosedEventHandler eh = (FormClosedEventHandler)(Events[FormClosedEvent]);
3146                         if (eh != null)
3147                                 eh (this, e);
3148
3149                         foreach (Form form in disabled_by_showdialog)
3150                         {
3151                                 form.Enabled = true;
3152                         }
3153                         disabled_by_showdialog.Clear();
3154                         if (modal_dialogs.Contains(this))
3155                                 modal_dialogs.Remove(this);
3156                 }
3157                 
3158                 // Consider calling FireClosingEvents instead of calling this directly.
3159                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3160                 protected virtual void OnFormClosing (FormClosingEventArgs e)
3161                 {
3162                         FormClosingEventHandler eh = (FormClosingEventHandler)(Events [FormClosingEvent]);
3163                         if (eh != null)
3164                                 eh (this, e);
3165                 }
3166
3167                 [MonoTODO ("Will never be called")]
3168                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3169                 protected virtual void OnHelpButtonClicked (CancelEventArgs e)
3170                 {
3171                         CancelEventHandler eh = (CancelEventHandler)(Events[HelpButtonClickedEvent]);
3172                         if (eh != null)
3173                                 eh (this, e);
3174                 }
3175
3176                 protected override void OnLayout (LayoutEventArgs levent)
3177                 {
3178                         base.OnLayout (levent);
3179                         
3180                         if (AutoSize) {
3181                                 Size new_size = GetPreferredSizeCore (Size.Empty);
3182                                 if (AutoSizeMode == AutoSizeMode.GrowOnly) {
3183                                         new_size.Width = Math.Max (new_size.Width, Width);
3184                                         new_size.Height = Math.Max (new_size.Height, Height);
3185                                 }
3186                                 if (new_size == Size)
3187                                         return;
3188
3189                                 SetBoundsInternal (bounds.X, bounds.Y, new_size.Width, new_size.Height, BoundsSpecified.None);
3190                         }
3191                 }
3192
3193                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3194                 protected virtual void OnResizeBegin (EventArgs e)
3195                 {
3196                         EventHandler eh = (EventHandler) (Events [ResizeBeginEvent]);
3197                         if (eh != null)
3198                                 eh (this, e);
3199                 }
3200
3201                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3202                 protected virtual void OnResizeEnd (EventArgs e)
3203                 {
3204                         EventHandler eh = (EventHandler) (Events [ResizeEndEvent]);
3205                         if (eh != null)
3206                                 eh (this, e);
3207                 }
3208
3209                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3210                 protected virtual void OnRightToLeftLayoutChanged (EventArgs e)
3211                 {
3212                         EventHandler eh = (EventHandler)(Events[RightToLeftLayoutChangedEvent]);
3213                         if (eh != null)
3214                                 eh (this, e);
3215                 }
3216
3217                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3218                 protected virtual void OnShown (EventArgs e)
3219                 {
3220                         EventHandler eh = (EventHandler) (Events [ShownEvent]);
3221                         if (eh != null)
3222                                 eh (this, e);
3223                 }
3224
3225                 #region UIA Framework Events
3226                 static object UIAMenuChangedEvent = new object ();
3227                 static object UIATopMostChangedEvent = new object ();
3228                 static object UIAWindowStateChangedEvent = new object ();
3229
3230                 internal event EventHandler UIAMenuChanged {
3231                         add { Events.AddHandler (UIAMenuChangedEvent, value); }
3232                         remove { Events.RemoveHandler (UIAMenuChangedEvent, value); }
3233                 }
3234
3235                 internal event EventHandler UIATopMostChanged {
3236                         add { Events.AddHandler (UIATopMostChangedEvent, value); }
3237                         remove { Events.RemoveHandler (UIATopMostChangedEvent, value); }
3238                 }
3239
3240                 internal event EventHandler UIAWindowStateChanged {
3241                         add { Events.AddHandler (UIAWindowStateChangedEvent, value); }
3242                         remove { Events.RemoveHandler (UIAWindowStateChangedEvent, value); }
3243                 }
3244
3245                 internal void OnUIAMenuChanged (EventArgs e)
3246                 {
3247                         EventHandler eh = (EventHandler) Events [UIAMenuChangedEvent];
3248                         if (eh != null)
3249                                 eh (this, e);
3250                 }
3251
3252                 internal void OnUIATopMostChanged ()
3253                 {
3254                         EventHandler eh = (EventHandler) Events [UIATopMostChangedEvent];
3255                         if (eh != null)
3256                                 eh (this, EventArgs.Empty);
3257                 }
3258
3259                 internal void OnUIAWindowStateChanged ()
3260                 {
3261                         EventHandler eh = (EventHandler) Events [UIAWindowStateChangedEvent];
3262                         if (eh != null)
3263                                 eh (this, EventArgs.Empty);
3264                 }
3265                 #endregion      // UIA Framework Events
3266                 #endregion      // Events
3267         }
3268 }