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