* Control.cs: We need to reset the is_created flags when the handle is
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / XplatUIWin32.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
27 // NOT COMPLETE
28
29 using System;
30 using System.Drawing;
31 using System.Drawing.Imaging;
32 using System.ComponentModel;
33 using System.Collections;
34 using System.Diagnostics;
35 using System.IO;
36 using System.Runtime.InteropServices;
37 using System.Text;
38
39
40 /// Win32 Version
41 namespace System.Windows.Forms {
42         internal class XplatUIWin32 : XplatUIDriver {
43                 #region Local Variables
44                 private static XplatUIWin32     instance;
45                 private static int              ref_count;
46                 private static IntPtr           FosterParent;
47
48                 internal static MouseButtons    mouse_state;
49                 internal static Point           mouse_position;
50                 internal static bool            grab_confined;
51                 internal static IntPtr          grab_hwnd;
52                 internal static Rectangle       grab_area;
53                 internal static WndProc         wnd_proc;
54                 internal static IntPtr          prev_mouse_hwnd;
55                 internal static IntPtr          override_cursor;
56                 internal static bool            caret_visible;
57
58                 internal static bool            themes_enabled;
59                 private Hashtable               timer_list;
60                 private static Queue            message_queue;
61                 private static IntPtr           clip_magic = new IntPtr(27051977);
62                 private static int              scroll_width;
63                 private static int              scroll_height;
64                 private static Hashtable        wm_nc_registered;
65                 private static RECT             clipped_cursor_rect;
66                 private Hashtable               registered_classes;
67                 private Hwnd HwndCreating; // the Hwnd we are currently creating (see CreateWindow)
68
69                 #endregion      // Local Variables
70
71                 #region Private Structs
72                 [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
73                 private struct WNDCLASS {
74                         internal int            style;
75                         internal WndProc        lpfnWndProc;
76                         internal int            cbClsExtra;
77                         internal int            cbWndExtra;
78                         internal IntPtr         hInstance;
79                         internal IntPtr         hIcon;
80                         internal IntPtr         hCursor;
81                         internal IntPtr         hbrBackground;
82                         [MarshalAs(UnmanagedType.LPWStr)]
83                         internal string         lpszMenuName;
84                         [MarshalAs(UnmanagedType.LPWStr)]
85                         internal string         lpszClassName;
86                 }
87
88                 [StructLayout(LayoutKind.Sequential)]
89                 internal struct RECT {
90                         internal int            left;
91                         internal int            top;
92                         internal int            right;
93                         internal int            bottom;
94
95                         public RECT (int left, int top, int right, int bottom)
96                         {
97                                 this.left = left;
98                                 this.top = top;
99                                 this.right = right;
100                                 this.bottom = bottom;
101                         }
102
103                         #region Instance Properties
104                         public int Height { get { return bottom - top; } }
105                         public int Width { get { return right - left; } }
106                         public Size Size { get { return new Size (Width, Height); } }
107                         public Point Location { get { return new Point (left, top); } }
108                         #endregion
109
110                         #region Instance Methods
111                         public Rectangle ToRectangle ()
112                         {
113                                 return Rectangle.FromLTRB (left, top, right, bottom);
114                         }
115
116                         public static RECT FromRectangle (Rectangle rectangle)
117                         {
118                                 return new RECT (rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom);
119                         }
120
121                         public override int GetHashCode ()
122                         {
123                                 return left ^ ((top << 13) | (top >> 0x13))
124                                   ^ ((Width << 0x1a) | (Width >> 6))
125                                   ^ ((Height << 7) | (Height >> 0x19));
126                         }
127                         
128                         public override string ToString ()
129                         {
130                                 return String.Format("RECT left={0}, top={1}, right={2}, bottom={3}, width={4}, height={5}", left, top, right, bottom, right-left, bottom-top);
131                         }
132                         #endregion
133
134                         #region Operator overloads
135                         public static implicit operator Rectangle (RECT rect)
136                         {
137                                 return Rectangle.FromLTRB (rect.left, rect.top, rect.right, rect.bottom);
138                         }
139
140                         public static implicit operator RECT (Rectangle rect)
141                         {
142                                 return new RECT (rect.Left, rect.Top, rect.Right, rect.Bottom);
143                         }
144                         #endregion
145                 }
146
147                 internal enum SPIAction {
148                         SPI_GETACTIVEWINDOWTRACKING = 0x1000,
149                         SPI_GETACTIVEWNDTRKTIMEOUT = 0x2002,
150                         SPI_GETANIMATION = 0x0048,
151                         SPI_GETCARETWIDTH = 0x2006,
152                         SPI_GETCOMBOBOXANIMATION = 0x1004,
153                         SPI_GETDRAGFULLWINDOWS  = 0x0026,
154                         SPI_GETDROPSHADOW = 0x1024,
155                         SPI_GETFONTSMOOTHING = 0x004A,
156                         SPI_GETFONTSMOOTHINGCONTRAST = 0x200C,
157                         SPI_GETFONTSMOOTHINGTYPE = 0x200A,
158                         SPI_GETGRADIENTCAPTIONS = 0x1008,
159                         SPI_GETHOTTRACKING = 0x100E,
160                         SPI_GETICONTITLEWRAP = 0x0019,
161                         SPI_GETKEYBOARDSPEED = 0x000A,
162                         SPI_GETKEYBOARDDELAY    = 0x0016,
163                         SPI_GETKEYBOARDCUES             = 0x100A,
164                         SPI_GETKEYBOARDPREF = 0x0044,
165                         SPI_GETLISTBOXSMOOTHSCROLLING = 0x1006,
166                         SPI_GETMENUANIMATION = 0x1002,
167                         SPI_GETMENUDROPALIGNMENT = 0x001B,
168                         SPI_GETMENUFADE = 0x1012,
169                         SPI_GETMENUSHOWDELAY = 0x006A,
170                         SPI_GETMOUSESPEED = 0x0070,
171                         SPI_GETSELECTIONFADE = 0x1014,
172                         SPI_GETSNAPTODEFBUTTON = 0x005F,
173                         SPI_GETTOOLTIPANIMATION = 0x1016,
174                         SPI_GETWORKAREA = 0x0030,
175                         SPI_GETMOUSEHOVERWIDTH  = 0x0062,
176                         SPI_GETMOUSEHOVERHEIGHT = 0x0064,
177                         SPI_GETMOUSEHOVERTIME   = 0x0066,
178                         SPI_GETUIEFFECTS = 0x103E,
179                         SPI_GETWHEELSCROLLLINES = 0x0068
180                 }
181
182                 internal enum WindowPlacementFlags {
183                         SW_HIDE                 = 0,
184                         SW_SHOWNORMAL           = 1,
185                         SW_NORMAL               = 1,
186                         SW_SHOWMINIMIZED        = 2,
187                         SW_SHOWMAXIMIZED        = 3,
188                         SW_MAXIMIZE             = 3,
189                         SW_SHOWNOACTIVATE       = 4,
190                         SW_SHOW                 = 5,
191                         SW_MINIMIZE             = 6,
192                         SW_SHOWMINNOACTIVE      = 7,
193                         SW_SHOWNA               = 8,
194                         SW_RESTORE              = 9,
195                         SW_SHOWDEFAULT          = 10,
196                         SW_FORCEMINIMIZE        = 11,
197                         SW_MAX                  = 11
198                 }
199
200                 [StructLayout(LayoutKind.Sequential)]
201                 private struct WINDOWPLACEMENT {
202                         internal uint                   length;
203                         internal uint                   flags;
204                         internal WindowPlacementFlags   showCmd;
205                         internal POINT                  ptMinPosition;
206                         internal POINT                  ptMaxPosition;
207                         internal RECT                   rcNormalPosition;
208                 }
209
210                 [StructLayout(LayoutKind.Sequential)]
211                 internal struct NCCALCSIZE_PARAMS {
212                         internal RECT           rgrc1;
213                         internal RECT           rgrc2;
214                         internal RECT           rgrc3;
215                         internal IntPtr         lppos;
216                 }
217
218                 [Flags]
219                 private enum TMEFlags {
220                         TME_HOVER               = 0x00000001,
221                         TME_LEAVE               = 0x00000002,
222                         TME_NONCLIENT           = 0x00000010,
223                         TME_QUERY               = unchecked((int)0x40000000),
224                         TME_CANCEL              = unchecked((int)0x80000000)
225                 }
226
227                 [StructLayout(LayoutKind.Sequential)]
228                 private struct TRACKMOUSEEVENT {
229                         internal int            size;
230                         internal TMEFlags       dwFlags;
231                         internal IntPtr         hWnd;
232                         internal int            dwHoverTime;
233                 }
234
235                 [StructLayout(LayoutKind.Sequential)]
236                 private struct PAINTSTRUCT {
237                         internal IntPtr         hdc;
238                         internal int            fErase;
239                         internal RECT           rcPaint;
240                         internal int            fRestore;
241                         internal int            fIncUpdate;
242                         internal int            Reserved1;
243                         internal int            Reserved2;
244                         internal int            Reserved3;
245                         internal int            Reserved4;
246                         internal int            Reserved5;
247                         internal int            Reserved6;
248                         internal int            Reserved7;
249                         internal int            Reserved8;
250                 }
251
252                 [StructLayout(LayoutKind.Sequential)]
253                 internal struct KEYBDINPUT {
254                         internal short wVk;
255                         internal short wScan;
256                         internal Int32 dwFlags;
257                         internal Int32 time;
258                         internal UIntPtr dwExtraInfo;
259                 }
260
261                 [StructLayout(LayoutKind.Sequential)]
262                 internal struct MOUSEINPUT {
263                         internal Int32 dx;
264                         internal Int32 dy;
265                         internal Int32 mouseData;
266                         internal Int32 dwFlags;
267                         internal Int32 time;
268                         internal UIntPtr dwExtraInfo;
269                 }
270
271                 [StructLayout(LayoutKind.Sequential)]
272                 internal struct HARDWAREINPUT {
273                         internal Int32 uMsg;
274                         internal short wParamL;
275                         internal short wParamH;
276                 }
277
278                 [StructLayout(LayoutKind.Explicit)]
279                 internal struct INPUT {
280                         [FieldOffset(0)]
281                         internal Int32 type;
282
283                         [FieldOffset(4)]
284                         internal MOUSEINPUT mi;
285
286                         [FieldOffset(4)]
287                         internal KEYBDINPUT ki;
288
289                         [FieldOffset(4)]
290                         internal HARDWAREINPUT hi;
291                 }
292
293                 [StructLayout (LayoutKind.Sequential)]
294                 public struct ANIMATIONINFO {
295                         internal uint cbSize;
296                         internal int iMinAnimate;
297                 }
298                 
299                 internal enum InputFlags {
300                         KEYEVENTF_EXTENDEDKEY   = 0x0001,
301                         KEYEVENTF_KEYUP                 = 0x0002,
302                         KEYEVENTF_SCANCODE              = 0x0003,
303                         KEYEVENTF_UNICODE               = 0x0004,
304                 }
305
306                 internal enum ClassStyle {
307                         CS_VREDRAW                      = 0x00000001,
308                         CS_HREDRAW                      = 0x00000002,
309                         CS_KEYCVTWINDOW                 = 0x00000004,
310                         CS_DBLCLKS                      = 0x00000008,
311                         CS_OWNDC                        = 0x00000020,
312                         CS_CLASSDC                      = 0x00000040,
313                         CS_PARENTDC                     = 0x00000080,
314                         CS_NOKEYCVT                     = 0x00000100,
315                         CS_NOCLOSE                      = 0x00000200,
316                         CS_SAVEBITS                     = 0x00000800,
317                         CS_BYTEALIGNCLIENT              = 0x00001000,
318                         CS_BYTEALIGNWINDOW              = 0x00002000,
319                         CS_GLOBALCLASS                  = 0x00004000,
320                         CS_IME                          = 0x00010000,
321                         // Windows XP+
322                         CS_DROPSHADOW                   = 0x00020000
323                 }
324
325                 internal enum SetWindowPosZOrder {
326                         HWND_TOP                        = 0,
327                         HWND_BOTTOM                     = 1,
328                         HWND_TOPMOST                    = -1,
329                         HWND_NOTOPMOST                  = -2
330                 }
331
332                 [Flags]
333                 internal enum SetWindowPosFlags {
334                         SWP_ASYNCWINDOWPOS              = 0x4000, 
335                         SWP_DEFERERASE                  = 0x2000,
336                         SWP_DRAWFRAME                   = 0x0020,
337                         SWP_FRAMECHANGED                = 0x0020,
338                         SWP_HIDEWINDOW                  = 0x0080,
339                         SWP_NOACTIVATE                  = 0x0010,
340                         SWP_NOCOPYBITS                  = 0x0100,
341                         SWP_NOMOVE                      = 0x0002,
342                         SWP_NOOWNERZORDER               = 0x0200,
343                         SWP_NOREDRAW                    = 0x0008,
344                         SWP_NOREPOSITION                = 0x0200,
345                         SWP_NOENDSCHANGING              = 0x0400,
346                         SWP_NOSIZE                      = 0x0001,
347                         SWP_NOZORDER                    = 0x0004,
348                         SWP_SHOWWINDOW                  = 0x0040
349                 }
350
351                 internal enum GetSysColorIndex {
352                         COLOR_SCROLLBAR                 = 0,
353                         COLOR_BACKGROUND                = 1,
354                         COLOR_ACTIVECAPTION             = 2,
355                         COLOR_INACTIVECAPTION           = 3,
356                         COLOR_MENU                      = 4,
357                         COLOR_WINDOW                    = 5,
358                         COLOR_WINDOWFRAME               = 6,
359                         COLOR_MENUTEXT                  = 7,
360                         COLOR_WINDOWTEXT                = 8,
361                         COLOR_CAPTIONTEXT               = 9,
362                         COLOR_ACTIVEBORDER              = 10,
363                         COLOR_INACTIVEBORDER            = 11,
364                         COLOR_APPWORKSPACE              = 12,
365                         COLOR_HIGHLIGHT                 = 13,
366                         COLOR_HIGHLIGHTTEXT             = 14,
367                         COLOR_BTNFACE                   = 15,
368                         COLOR_BTNSHADOW                 = 16,
369                         COLOR_GRAYTEXT                  = 17,
370                         COLOR_BTNTEXT                   = 18,
371                         COLOR_INACTIVECAPTIONTEXT       = 19,
372                         COLOR_BTNHIGHLIGHT              = 20,
373                         COLOR_3DDKSHADOW                = 21,
374                         COLOR_3DLIGHT                   = 22,
375                         COLOR_INFOTEXT                  = 23,
376                         COLOR_INFOBK                    = 24,
377                         
378                         COLOR_HOTLIGHT                  = 26,
379                         COLOR_GRADIENTACTIVECAPTION     = 27,
380                         COLOR_GRADIENTINACTIVECAPTION   = 28,
381                         COLOR_MENUHIGHLIGHT             = 29,
382                         COLOR_MENUBAR                   = 30,
383
384                         COLOR_DESKTOP                   = 1,
385                         COLOR_3DFACE                    = 16,
386                         COLOR_3DSHADOW                  = 16,
387                         COLOR_3DHIGHLIGHT               = 20,
388                         COLOR_3DHILIGHT                 = 20,
389                         COLOR_BTNHILIGHT                = 20,
390                         COLOR_MAXVALUE                  = 24,/* Maximum value */
391                 }       
392
393                 private enum LoadCursorType {
394                         First                           = 32512,
395                         IDC_ARROW                       = 32512,
396                         IDC_IBEAM                       = 32513,
397                         IDC_WAIT                        = 32514,
398                         IDC_CROSS                       = 32515,
399                         IDC_UPARROW                     = 32516,
400                         IDC_SIZE                        = 32640,
401                         IDC_ICON                        = 32641,
402                         IDC_SIZENWSE                    = 32642,
403                         IDC_SIZENESW                    = 32643,
404                         IDC_SIZEWE                      = 32644,
405                         IDC_SIZENS                      = 32645,
406                         IDC_SIZEALL                     = 32646,
407                         IDC_NO                          = 32648,
408                         IDC_HAND                        = 32649,
409                         IDC_APPSTARTING                 = 32650,
410                         IDC_HELP                        = 32651,
411                         Last                            = 32651
412                 }
413
414                 private enum AncestorType {
415                         GA_PARENT = 1,
416                         GA_ROOT = 2, 
417                         GA_ROOTOWNER = 3
418                 }
419
420                 [Flags]
421                 private enum WindowLong {
422                         GWL_WNDPROC                     = -4,
423                         GWL_HINSTANCE                   = -6,
424                         GWL_HWNDPARENT                  = -8,
425                         GWL_STYLE                       = -16,
426                         GWL_EXSTYLE                     = -20,
427                         GWL_USERDATA                    = -21,
428                         GWL_ID                          = -12
429                 }
430
431                 [Flags]
432                 private enum LogBrushStyle {
433                         BS_SOLID                        = 0,
434                         BS_NULL                         = 1,
435                         BS_HATCHED                      = 2,
436                         BS_PATTERN                      = 3,
437                         BS_INDEXED                      = 4,
438                         BS_DIBPATTERN                   = 5,
439                         BS_DIBPATTERNPT                 = 6,
440                         BS_PATTERN8X8                   = 7,
441                         BS_DIBPATTERN8X8                = 8,
442                         BS_MONOPATTERN                  = 9
443                 }
444
445                 [Flags]
446                 private enum LogBrushHatch {
447                         HS_HORIZONTAL                   = 0,       /* ----- */
448                         HS_VERTICAL                     = 1,       /* ||||| */
449                         HS_FDIAGONAL                    = 2,       /* \\\\\ */
450                         HS_BDIAGONAL                    = 3,       /* ///// */
451                         HS_CROSS                        = 4,       /* +++++ */
452                         HS_DIAGCROSS                    = 5,       /* xxxxx */
453                 }
454
455                 internal struct COLORREF {
456                         internal byte                   R;
457                         internal byte                   G;
458                         internal byte                   B;
459                         internal byte                   A;
460                 }
461
462                 [StructLayout(LayoutKind.Sequential)]
463                 private struct LOGBRUSH {
464                         internal LogBrushStyle          lbStyle;
465                         internal COLORREF               lbColor;
466                         internal LogBrushHatch          lbHatch;
467                 }
468
469                 [StructLayout(LayoutKind.Sequential)]
470                 internal struct TEXTMETRIC { 
471                         internal int                    tmHeight;
472                         internal int                    tmAscent;
473                         internal int                    tmDescent;
474                         internal int                    tmInternalLeading;
475                         internal int                    tmExternalLeading;
476                         internal int                    tmAveCharWidth;
477                         internal int                    tmMaxCharWidth;
478                         internal int                    tmWeight;
479                         internal int                    tmOverhang;
480                         internal int                    tmDigitizedAspectX;
481                         internal int                    tmDigitizedAspectY;
482                         internal short                  tmFirstChar; 
483                         internal short                  tmLastChar; 
484                         internal short                  tmDefaultChar; 
485                         internal short                  tmBreakChar; 
486                         internal byte                   tmItalic; 
487                         internal byte                   tmUnderlined; 
488                         internal byte                   tmStruckOut; 
489                         internal byte                   tmPitchAndFamily; 
490                         internal byte                   tmCharSet; 
491                 }
492
493                 public enum TernaryRasterOperations : uint
494                 {
495                         SRCCOPY = 0x00CC0020,
496                         SRCPAINT = 0x00EE0086,
497                         SRCAND = 0x008800C6,
498                         SRCINVERT = 0x00660046,
499                         SRCERASE = 0x00440328,
500                         NOTSRCCOPY = 0x00330008,
501                         NOTSRCERASE = 0x001100A6,
502                         MERGECOPY = 0x00C000CA,
503                         MERGEPAINT = 0x00BB0226,
504                         PATCOPY = 0x00F00021,
505                         PATPAINT = 0x00FB0A09,
506                         PATINVERT = 0x005A0049,
507                         DSTINVERT = 0x00550009,
508                         BLACKNESS = 0x00000042,
509                         WHITENESS = 0x00FF0062
510                 }
511
512                 [Flags]
513                 private enum ScrollWindowExFlags {
514                         SW_NONE                         = 0x0000,
515                         SW_SCROLLCHILDREN               = 0x0001,
516                         SW_INVALIDATE                   = 0x0002,
517                         SW_ERASE                        = 0x0004,
518                         SW_SMOOTHSCROLL                 = 0x0010
519                 }
520
521                 internal enum SystemMetrics {
522                         SM_CXSCREEN                     = 0,
523                         SM_CYSCREEN                     = 1,
524                         SM_CXVSCROLL                    = 2,
525                         SM_CYHSCROLL                    = 3,
526                         SM_CYCAPTION                    = 4,
527                         SM_CXBORDER                     = 5,
528                         SM_CYBORDER                     = 6,
529                         SM_CXDLGFRAME                   = 7,
530                         SM_CYDLGFRAME                   = 8,
531                         SM_CYVTHUMB                     = 9,
532                         SM_CXHTHUMB                     = 10,
533                         SM_CXICON                       = 11,
534                         SM_CYICON                       = 12,
535                         SM_CXCURSOR                     = 13,
536                         SM_CYCURSOR                     = 14,
537                         SM_CYMENU                       = 15,
538                         SM_CXFULLSCREEN                 = 16,
539                         SM_CYFULLSCREEN                 = 17,
540                         SM_CYKANJIWINDOW                = 18,
541                         SM_MOUSEPRESENT                 = 19,
542                         SM_CYVSCROLL                    = 20,
543                         SM_CXHSCROLL                    = 21,
544                         SM_DEBUG                        = 22,
545                         SM_SWAPBUTTON                   = 23,
546                         SM_RESERVED1                    = 24,
547                         SM_RESERVED2                    = 25,
548                         SM_RESERVED3                    = 26,
549                         SM_RESERVED4                    = 27,
550                         SM_CXMIN                        = 28,
551                         SM_CYMIN                        = 29,
552                         SM_CXSIZE                       = 30,
553                         SM_CYSIZE                       = 31,
554                         SM_CXFRAME                      = 32,
555                         SM_CYFRAME                      = 33,
556                         SM_CXMINTRACK                   = 34,
557                         SM_CYMINTRACK                   = 35,
558                         SM_CXDOUBLECLK                  = 36,
559                         SM_CYDOUBLECLK                  = 37,
560                         SM_CXICONSPACING                = 38,
561                         SM_CYICONSPACING                = 39,
562                         SM_MENUDROPALIGNMENT            = 40,
563                         SM_PENWINDOWS                   = 41,
564                         SM_DBCSENABLED                  = 42,
565                         SM_CMOUSEBUTTONS                = 43,
566                         SM_CXFIXEDFRAME                 = SM_CXDLGFRAME,
567                         SM_CYFIXEDFRAME                 = SM_CYDLGFRAME,
568                         SM_CXSIZEFRAME                  = SM_CXFRAME,
569                         SM_CYSIZEFRAME                  = SM_CYFRAME,
570                         SM_SECURE                       = 44,
571                         SM_CXEDGE                       = 45,
572                         SM_CYEDGE                       = 46,
573                         SM_CXMINSPACING                 = 47,
574                         SM_CYMINSPACING                 = 48,
575                         SM_CXSMICON                     = 49,
576                         SM_CYSMICON                     = 50,
577                         SM_CYSMCAPTION                  = 51,
578                         SM_CXSMSIZE                     = 52,
579                         SM_CYSMSIZE                     = 53,
580                         SM_CXMENUSIZE                   = 54,
581                         SM_CYMENUSIZE                   = 55,
582                         SM_ARRANGE                      = 56,
583                         SM_CXMINIMIZED                  = 57,
584                         SM_CYMINIMIZED                  = 58,
585                         SM_CXMAXTRACK                   = 59,
586                         SM_CYMAXTRACK                   = 60,
587                         SM_CXMAXIMIZED                  = 61,
588                         SM_CYMAXIMIZED                  = 62,
589                         SM_NETWORK                      = 63,
590                         SM_CLEANBOOT                    = 67,
591                         SM_CXDRAG                       = 68,
592                         SM_CYDRAG                       = 69,
593                         SM_SHOWSOUNDS                   = 70,
594                         SM_CXMENUCHECK                  = 71,
595                         SM_CYMENUCHECK                  = 72,
596                         SM_SLOWMACHINE                  = 73,
597                         SM_MIDEASTENABLED               = 74,
598                         SM_MOUSEWHEELPRESENT            = 75,
599                         SM_XVIRTUALSCREEN               = 76,
600                         SM_YVIRTUALSCREEN               = 77,
601                         SM_CXVIRTUALSCREEN              = 78,
602                         SM_CYVIRTUALSCREEN              = 79,
603                         SM_CMONITORS                    = 80,
604                         SM_SAMEDISPLAYFORMAT            = 81,
605                         SM_IMMENABLED                   = 82,
606                         SM_CXFOCUSBORDER                = 83,
607                         SM_CYFOCUSBORDER                = 84,
608                         SM_TABLETPC                     = 86,
609                         SM_MEDIACENTER                  = 87,
610                         SM_CMETRICS                     = 88
611                 }
612
613                 // We'll only support _WIN32_IE < 0x0500 for now
614                 internal enum NotifyIconMessage {
615                         NIM_ADD                         = 0x00000000,
616                         NIM_MODIFY                      = 0x00000001,
617                         NIM_DELETE                      = 0x00000002,
618                 }
619
620                 [Flags]
621                 internal enum NotifyIconFlags {
622                         NIF_MESSAGE                     = 0x00000001,
623                         NIF_ICON                        = 0x00000002,
624                         NIF_TIP                         = 0x00000004,
625                         NIF_STATE                       = 0x00000008,
626                         NIF_INFO                        = 0x00000010                    
627                 }
628
629                 [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
630                 internal struct NOTIFYICONDATA {
631                         internal uint                           cbSize;
632                         internal IntPtr                         hWnd;
633                         internal uint                           uID;
634                         internal NotifyIconFlags        uFlags;
635                         internal uint                           uCallbackMessage;
636                         internal IntPtr                         hIcon;
637                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
638                         internal string                         szTip;
639                         internal int                            dwState;
640                         internal int                            dwStateMask;
641                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
642                         internal string                         szInfo;
643                         internal int                            uTimeoutOrVersion;
644                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]
645                         internal string                         szInfoTitle;
646 #if NET_2_0
647                         internal ToolTipIcon            dwInfoFlags;
648 #else
649                         internal int                            dwInfoFlags;
650 #endif
651                 }
652
653                 [Flags]
654                 internal enum DCExFlags {
655                         DCX_WINDOW                      = 0x00000001,
656                         DCX_CACHE                       = 0x00000002,
657                         DCX_NORESETATTRS                = 0x00000004,
658                         DCX_CLIPCHILDREN                = 0x00000008,
659                         DCX_CLIPSIBLINGS                = 0x00000010,
660                         DCX_PARENTCLIP                  = 0x00000020,
661                         DCX_EXCLUDERGN                  = 0x00000040,
662                         DCX_INTERSECTRGN                = 0x00000080,
663                         DCX_EXCLUDEUPDATE               = 0x00000100,
664                         DCX_INTERSECTUPDATE             = 0x00000200,
665                         DCX_LOCKWINDOWUPDATE            = 0x00000400,
666                         DCX_USESTYLE                    = 0x00010000,
667                         DCX_VALIDATE                    = 0x00200000
668                 }
669
670                 [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
671                 internal struct CLIENTCREATESTRUCT {
672                         internal IntPtr                 hWindowMenu;
673                         internal uint                   idFirstChild;
674                 }
675
676                 private enum ClassLong : int {
677                         GCL_MENUNAME                    = -8,
678                         GCL_HBRBACKGROUND               = -10,
679                         GCL_HCURSOR                     = -12,
680                         GCL_HICON                       = -14,
681                         GCL_HMODULE                     = -16,
682                         GCL_CBWNDEXTRA                  = -18,
683                         GCL_CBCLSEXTRA                  = -20,
684                         GCL_WNDPROC                     = -24,
685                         GCL_STYLE                       = -26,
686                         GCW_ATOM                        = -32,
687                         GCL_HICONSM                     = -34
688                 }
689
690                 [Flags]
691                 internal enum GAllocFlags : uint {
692                         GMEM_FIXED                      = 0x0000,
693                         GMEM_MOVEABLE                   = 0x0002,
694                         GMEM_NOCOMPACT                  = 0x0010,
695                         GMEM_NODISCARD                  = 0x0020,
696                         GMEM_ZEROINIT                   = 0x0040,
697                         GMEM_MODIFY                     = 0x0080,
698                         GMEM_DISCARDABLE                = 0x0100,
699                         GMEM_NOT_BANKED                 = 0x1000,
700                         GMEM_SHARE                      = 0x2000,
701                         GMEM_DDESHARE                   = 0x2000,
702                         GMEM_NOTIFY                     = 0x4000,
703                         GMEM_LOWER                      = GMEM_NOT_BANKED,
704                         GMEM_VALID_FLAGS                = 0x7F72,
705                         GMEM_INVALID_HANDLE             = 0x8000,
706                         GHND                            = (GMEM_MOVEABLE | GMEM_ZEROINIT),
707                         GPTR                            = (GMEM_FIXED | GMEM_ZEROINIT)
708                 }
709
710                 internal enum ROP2DrawMode : int {
711                         R2_BLACK                        = 1,
712                         R2_NOTMERGEPEN                  = 2,
713                         R2_MASKNOTPEN                   = 3,
714                         R2_NOTCOPYPEN                   = 4,
715                         R2_MASKPENNOT                   = 5,
716                         R2_NOT                          = 6,
717                         R2_XORPEN                       = 7,
718                         R2_NOTMASKPEN                   = 8,
719                         R2_MASKPEN                      = 9,
720                         R2_NOTXORPEN                    = 10,
721                         R2_NOP                          = 11,
722                         R2_MERGENOTPEN                  = 12,
723                         R2_COPYPEN                      = 13,
724                         R2_MERGEPENNOT                  = 14,
725                         R2_MERGEPEN                     = 15,
726                         R2_WHITE                        = 16,
727                         R2_LAST                         = 16
728                 }
729
730                 internal enum PenStyle : int {
731                         PS_SOLID                        = 0,
732                         PS_DASH                         = 1,
733                         PS_DOT                          = 2,
734                         PS_DASHDOT                      = 3,
735                         PS_DASHDOTDOT                   = 4,
736                         PS_NULL                         = 5,
737                         PS_INSIDEFRAME                  = 6,
738                         PS_USERSTYLE                    = 7,
739                         PS_ALTERNATE                    = 8
740                 }
741
742                 internal enum PatBltRop : int {
743                         PATCOPY   = 0xf00021,
744                         PATINVERT = 0x5a0049,
745                         DSTINVERT = 0x550009,
746                         BLACKNESS = 0x000042,
747                         WHITENESS = 0xff0062,
748                 }
749
750                 internal enum StockObject : int {
751                         WHITE_BRUSH                     = 0,
752                         LTGRAY_BRUSH                    = 1,
753                         GRAY_BRUSH                      = 2,
754                         DKGRAY_BRUSH                    = 3,
755                         BLACK_BRUSH                     = 4,
756                         NULL_BRUSH                      = 5,
757                         HOLLOW_BRUSH                    = NULL_BRUSH,
758                         WHITE_PEN                       = 6,
759                         BLACK_PEN                       = 7,
760                         NULL_PEN                        = 8,
761                         OEM_FIXED_FONT                  = 10,
762                         ANSI_FIXED_FONT                 = 11,
763                         ANSI_VAR_FONT                   = 12,
764                         SYSTEM_FONT                     = 13,
765                         DEVICE_DEFAULT_FONT             = 14,
766                         DEFAULT_PALETTE                 = 15,
767                         SYSTEM_FIXED_FONT               = 16
768                 }
769
770                 internal enum HatchStyle : int {
771                         HS_HORIZONTAL                   = 0,
772                         HS_VERTICAL                     = 1,
773                         HS_FDIAGONAL                    = 2,
774                         HS_BDIAGONAL                    = 3,
775                         HS_CROSS                        = 4,
776                         HS_DIAGCROSS                    = 5
777                 }
778
779                 [Flags]
780                 internal enum SndFlags : int {
781                         SND_SYNC                        = 0x0000,
782                         SND_ASYNC                       = 0x0001,
783                         SND_NODEFAULT                   = 0x0002,
784                         SND_MEMORY                      = 0x0004,
785                         SND_LOOP                        = 0x0008,
786                         SND_NOSTOP                      = 0x0010,
787                         SND_NOWAIT                      = 0x00002000,
788                         SND_ALIAS                       = 0x00010000,
789                         SND_ALIAS_ID                    = 0x00110000,
790                         SND_FILENAME                    = 0x00020000,
791                         SND_RESOURCE                    = 0x00040004,
792                         SND_PURGE                       = 0x0040,
793                         SND_APPLICATION                 = 0x0080,
794                 }
795
796                 [Flags]
797                 internal enum LayeredWindowAttributes : int {
798                         LWA_COLORKEY            = 0x1,
799                         LWA_ALPHA                       = 0x2,
800                 }
801
802                 public enum ACLineStatus : byte {
803                         Offline = 0,
804                         Online = 1,
805                         Unknown = 255
806                 }
807
808                 public enum BatteryFlag : byte {
809                         High = 1,
810                         Low = 2,
811                         Critical = 4,
812                         Charging = 8,
813                         NoSystemBattery = 128,
814                         Unknown = 255
815                 }
816
817                 [StructLayout (LayoutKind.Sequential)]
818                 public class SYSTEMPOWERSTATUS {
819                         public ACLineStatus _ACLineStatus;
820                         public BatteryFlag _BatteryFlag;
821                         public Byte _BatteryLifePercent;
822                         public Byte _Reserved1;
823                         public Int32 _BatteryLifeTime;
824                         public Int32 _BatteryFullLifeTime;
825                 }
826                 #endregion
827
828                 #region Constructor & Destructor
829                 private XplatUIWin32() {
830                         // Handle singleton stuff first
831                         ref_count=0;
832
833                         mouse_state = MouseButtons.None;
834                         mouse_position = Point.Empty;
835
836                         message_queue = new Queue();
837
838                         themes_enabled = false;
839
840                         wnd_proc = new WndProc(InternalWndProc);
841
842                         FosterParent=Win32CreateWindow(WindowExStyles.WS_EX_TOOLWINDOW, "static", "Foster Parent Window", WindowStyles.WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
843
844                         if (FosterParent==IntPtr.Zero) {
845                                 Win32MessageBox(IntPtr.Zero, "Could not create foster window, win32 error " + Win32GetLastError().ToString(), "Oops", 0);
846                         }
847
848                         scroll_height = Win32GetSystemMetrics(SystemMetrics.SM_CYHSCROLL);
849                         scroll_width = Win32GetSystemMetrics(SystemMetrics.SM_CXVSCROLL);
850
851                         timer_list = new Hashtable ();
852                         registered_classes = new Hashtable ();
853                 }
854                 #endregion      // Constructor & Destructor
855
856                 #region Private Support Methods
857
858                 private string RegisterWindowClass (int classStyle)
859                 {
860                         string class_name;
861
862                         lock (registered_classes) {
863                                 class_name = (string)registered_classes[classStyle];
864
865                                 if (class_name != null)
866                                         return class_name;
867
868                                 class_name = string.Format ("Mono.WinForms.{0}.{1}", System.Threading.Thread.GetDomainID ().ToString (), classStyle);
869
870                                 WNDCLASS wndClass;
871
872                                 wndClass.style = classStyle;
873                                 wndClass.lpfnWndProc = wnd_proc;
874                                 wndClass.cbClsExtra = 0;
875                                 wndClass.cbWndExtra = 0;
876                                 wndClass.hbrBackground = (IntPtr)(GetSysColorIndex.COLOR_WINDOW + 1);
877                                 wndClass.hCursor = Win32LoadCursor (IntPtr.Zero, LoadCursorType.IDC_ARROW);
878                                 wndClass.hIcon = IntPtr.Zero;
879                                 wndClass.hInstance = IntPtr.Zero;
880                                 wndClass.lpszClassName = class_name;
881                                 wndClass.lpszMenuName = "";
882
883                                 bool result = Win32RegisterClass (ref wndClass);
884
885                                 if (result == false)
886                                         Win32MessageBox (IntPtr.Zero, "Could not register the window class, win32 error " + Win32GetLastError ().ToString (), "Oops", 0);
887
888                                 registered_classes[classStyle] = class_name;
889                         }
890                         
891                         return class_name;
892                 }
893
894                 private static bool RetrieveMessage(ref MSG msg) {
895                         MSG     message;
896
897                         if (message_queue.Count == 0) {
898                                 return false;
899                         }
900
901                         message = (MSG)message_queue.Dequeue();
902                         msg = message;
903
904                         return true;
905                 }
906
907                 private static bool StoreMessage(ref MSG msg) {
908                         MSG message = new MSG();
909
910                         message = msg;
911                         message_queue.Enqueue(message);
912
913                         return true;
914                 }
915
916                 internal static String AnsiToString(IntPtr ansi_data) {
917                         return (string)Marshal.PtrToStringAnsi(ansi_data);
918                 }
919
920                 internal static String UnicodeToString(IntPtr unicode_data) {
921                         return (string)Marshal.PtrToStringUni(unicode_data);
922                 }
923
924                 internal static Image DIBtoImage(IntPtr dib_data) {
925                         BITMAPINFOHEADER        bmi;
926                         int                     ncolors;
927                         int                     imagesize;
928                         //int                   palettesize;
929                         Bitmap                  bmp;
930                         BitmapData              bits;
931                         ColorPalette            pal;
932                         int[]                   palette;
933                         byte[]                  imagebits;
934                         int                     bytesPerLine;
935
936                         bmi = (BITMAPINFOHEADER)Marshal.PtrToStructure(dib_data, typeof(BITMAPINFOHEADER));
937
938                         ncolors = (int)bmi.biClrUsed;
939                         if (ncolors == 0) {
940                                 if (bmi.biBitCount < 24) {
941                                         ncolors = (int)(1 << bmi.biBitCount);
942                                 }
943                         }
944                         //palettesize = ncolors * 4;
945
946                         imagesize = (int)bmi.biSizeImage;
947                         if (imagesize == 0) {
948                                 imagesize = (int)(((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight);
949                         }
950
951                         switch(bmi.biBitCount) {
952                                 case 1: {       // Monochrome
953                                         bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format1bppIndexed);
954                                         palette = new int[2];
955                                         break;
956                                 }
957
958                                 case 4: {       // 4bpp
959                                         bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format4bppIndexed);
960                                         palette = new int[16];
961                                         break;
962                                 }
963
964                                 case 8: {       // 8bpp
965                                         bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format8bppIndexed);
966                                         palette = new int[256];
967                                         break;
968                                 }
969
970                                 case 24:
971                                 case 32: {      // 32bpp
972                                         bmp = new Bitmap(bmi.biWidth, bmi.biHeight, PixelFormat.Format32bppArgb);
973                                         palette = new int[0];
974                                         break;
975                                 }
976
977                                 default: {
978                                         throw new Exception("Unexpected number of bits:" + bmi.biBitCount.ToString());
979                                 }
980                         }
981
982                         if (bmi.biBitCount < 24) {
983                                 pal = bmp.Palette;                              // Managed palette
984                                 Marshal.Copy((IntPtr)((int)dib_data + Marshal.SizeOf(typeof(BITMAPINFOHEADER))), palette, 0, palette.Length);
985
986                                 for (int i = 0; i < ncolors; i++) {
987                                         pal.Entries[i] = Color.FromArgb(palette[i] | unchecked((int)0xff000000));
988                                 }
989                                 bmp.Palette = pal;
990                         }
991
992                         bytesPerLine = (int)((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3);
993                         bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
994
995                         imagebits = new byte[bytesPerLine];
996
997                         for (int y = 0; y < bmi.biHeight; y++) {
998                                 // Copy from source to managed
999                                 Marshal.Copy((IntPtr)((int)dib_data + Marshal.SizeOf(typeof(BITMAPINFOHEADER)) + palette.Length * 4 + bytesPerLine * y), imagebits, 0, bytesPerLine);
1000
1001                                 // Copy from managed to dest
1002                                 Marshal.Copy(imagebits, 0, (IntPtr)((int)bits.Scan0 + bits.Stride * (bmi.biHeight - 1 - y)), imagebits.Length);
1003                         }
1004
1005                         bmp.UnlockBits(bits);
1006
1007                         return bmp;
1008                 }
1009
1010                 internal static byte[] ImageToDIB(Image image) {
1011                         MemoryStream    ms;
1012                         byte[]          buffer;
1013                         byte[]          retbuf;
1014
1015                         ms = new MemoryStream();
1016                         image.Save(ms, ImageFormat.Bmp);
1017                         buffer = ms.GetBuffer();
1018
1019                         // Filter out the file header
1020                         retbuf = new byte[buffer.Length];
1021                         Array.Copy(buffer, 14, retbuf, 0, buffer.Length - 14);
1022                         return retbuf;
1023                 }
1024
1025                 internal static IntPtr DupGlobalMem(IntPtr mem) {
1026                         IntPtr  dup;
1027                         IntPtr  dup_ptr;
1028                         IntPtr  mem_ptr;
1029                         uint    len;
1030
1031                         len = Win32GlobalSize(mem);
1032                         mem_ptr = Win32GlobalLock(mem);
1033
1034                         dup = Win32GlobalAlloc(GAllocFlags.GMEM_MOVEABLE, (int)len);
1035                         dup_ptr = Win32GlobalLock(dup);
1036
1037                         Win32CopyMemory(dup_ptr, mem_ptr, (int)len);
1038
1039                         Win32GlobalUnlock(mem);
1040                         Win32GlobalUnlock(dup);
1041
1042                         return dup;
1043                 }
1044                 
1045                 private int GetSystemParametersInfoInt (SPIAction spi)
1046                 {
1047                         int value = 0;
1048                         
1049                         Win32SystemParametersInfo (spi, 0, ref value, 0);
1050                         
1051                         return value;
1052                 }
1053
1054                 private bool GetSystemParametersInfoBool (SPIAction spi)
1055                 {
1056                         bool value = false;
1057                         
1058                         Win32SystemParametersInfo (spi, 0, ref value, 0);
1059
1060                         return value;
1061                 }
1062                 #endregion      // Private Support Methods
1063
1064                 #region Static Properties
1065                 internal override int ActiveWindowTrackingDelay {
1066                         get { return GetSystemParametersInfoInt (SPIAction.SPI_GETACTIVEWNDTRKTIMEOUT); }
1067                 }
1068
1069                 internal override int CaretWidth {
1070                         get { 
1071                                 // Supported on 2k, XP, 2k3 +
1072                                 if (Environment.OSVersion.Version.Major < 5)
1073                                         throw new NotSupportedException ();
1074                                         
1075                                 return GetSystemParametersInfoInt (SPIAction.SPI_GETCARETWIDTH);
1076                         }
1077                 }
1078
1079                 internal override int FontSmoothingContrast {
1080                         get {
1081                                 // Supported on XP, 2k3 +
1082                                 if (Environment.OSVersion.Version.Major < 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 0))
1083                                         throw new NotSupportedException ();
1084                                         
1085                                 return GetSystemParametersInfoInt (SPIAction.SPI_GETFONTSMOOTHINGCONTRAST);
1086                         }
1087                 }
1088
1089                 internal override int FontSmoothingType {
1090                         get {
1091                                 // Supported on XP, 2k3 +
1092                                 if (Environment.OSVersion.Version.Major < 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 0))
1093                                         throw new NotSupportedException ();
1094
1095                                 return GetSystemParametersInfoInt (SPIAction.SPI_GETFONTSMOOTHINGTYPE);
1096                         }
1097                 }
1098
1099                 internal override int HorizontalResizeBorderThickness {
1100                         get { return Win32GetSystemMetrics (SystemMetrics.SM_CXSIZEFRAME); }
1101                 }
1102
1103                 internal override bool IsActiveWindowTrackingEnabled {
1104                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETACTIVEWINDOWTRACKING); }
1105                 }
1106
1107                 internal override bool IsComboBoxAnimationEnabled {
1108                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETCOMBOBOXANIMATION); }
1109                 }
1110
1111                 internal override bool IsDropShadowEnabled {
1112                         get {
1113                                 // Supported on XP, 2k3 +
1114                                 if (Environment.OSVersion.Version.Major < 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 0))
1115                                         throw new NotSupportedException ();
1116
1117                                 return GetSystemParametersInfoBool (SPIAction.SPI_GETDROPSHADOW);
1118                         }
1119                 }
1120
1121                 internal override bool IsFontSmoothingEnabled {
1122                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETFONTSMOOTHING); }
1123                 }
1124
1125                 internal override bool IsHotTrackingEnabled {
1126                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETHOTTRACKING); }
1127                 }
1128
1129                 internal override bool IsIconTitleWrappingEnabled {
1130                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETICONTITLEWRAP); }
1131                 }
1132
1133                 internal override bool IsKeyboardPreferred {
1134                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETKEYBOARDPREF); }
1135                 }
1136
1137                 internal override bool IsListBoxSmoothScrollingEnabled {
1138                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETLISTBOXSMOOTHSCROLLING); }
1139                 }
1140
1141                 internal override bool IsMenuAnimationEnabled {
1142                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETMENUANIMATION); }
1143                 }
1144
1145                 internal override bool IsMenuFadeEnabled {
1146                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETMENUFADE); }
1147                 }
1148
1149                 internal override bool IsMinimizeRestoreAnimationEnabled {
1150                         get {
1151                                 ANIMATIONINFO ai = new ANIMATIONINFO ();
1152                                 ai.cbSize = (uint)Marshal.SizeOf (ai);
1153                                 
1154                                 Win32SystemParametersInfo (SPIAction.SPI_GETANIMATION, 0, ref ai, 0);
1155                                 return ai.iMinAnimate == 0 ? false : true;
1156                         }
1157                 }
1158
1159                 internal override bool IsSelectionFadeEnabled {
1160                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETSELECTIONFADE); }
1161                 }
1162
1163                 internal override bool IsSnapToDefaultEnabled {
1164                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETSNAPTODEFBUTTON); }
1165                 }
1166
1167                 internal override bool IsTitleBarGradientEnabled {
1168                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETGRADIENTCAPTIONS); }
1169                 }
1170
1171                 internal override bool IsToolTipAnimationEnabled {
1172                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETTOOLTIPANIMATION); }
1173                 }
1174
1175                 internal override Size MenuBarButtonSize {
1176                         get {
1177                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXMENUSIZE),
1178                                         Win32GetSystemMetrics (SystemMetrics.SM_CYMENUSIZE));
1179                         }
1180                 }
1181
1182                 internal override int MenuShowDelay {
1183                         get { return GetSystemParametersInfoInt (SPIAction.SPI_GETMENUSHOWDELAY); }
1184                 }
1185
1186                 internal override int MouseSpeed {
1187                         get { return GetSystemParametersInfoInt (SPIAction.SPI_GETMOUSESPEED); }
1188                 }
1189
1190                 internal override LeftRightAlignment PopupMenuAlignment {
1191                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETMENUDROPALIGNMENT) == true ? LeftRightAlignment.Left : LeftRightAlignment.Right; }
1192                 }
1193
1194 #if NET_2_0
1195                 internal override PowerStatus PowerStatus {
1196                         get {
1197                                 SYSTEMPOWERSTATUS p = new SYSTEMPOWERSTATUS ();
1198                                 
1199                                 Win32GetSystemPowerStatus (p);
1200                                 
1201                                 PowerStatus ps = new PowerStatus ((BatteryChargeStatus)p._BatteryFlag, p._BatteryFullLifeTime, (float)p._BatteryLifePercent / 255f, p._BatteryLifeTime, (PowerLineStatus)p._ACLineStatus);
1202                                 
1203                                 return ps;
1204                         }
1205                 }
1206 #endif
1207
1208                 internal override int SizingBorderWidth {
1209                         get { return Win32GetSystemMetrics (SystemMetrics.SM_CXSIZEFRAME); }
1210                 }
1211
1212                 internal override Size SmallCaptionButtonSize {
1213                         get {
1214                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXSMSIZE),
1215                                         Win32GetSystemMetrics (SystemMetrics.SM_CYSMSIZE));
1216                         }
1217                 }
1218
1219                 internal override bool UIEffectsEnabled {
1220                         get { return GetSystemParametersInfoBool (SPIAction.SPI_GETUIEFFECTS); }
1221                 }
1222
1223                 internal override int VerticalResizeBorderThickness {
1224                         get { return Win32GetSystemMetrics (SystemMetrics.SM_CYSIZEFRAME); }
1225                 }
1226
1227                 internal override void RaiseIdle (EventArgs e)
1228                 {
1229                         if (Idle != null)
1230                                 Idle (this, e);
1231                 }
1232
1233                 internal override Keys ModifierKeys {
1234                         get {
1235                                 short   state;
1236                                 Keys    key_state;
1237
1238                                 key_state = Keys.None;
1239
1240                                 state = Win32GetKeyState(VirtualKeys.VK_SHIFT);
1241                                 if ((state & 0x8000) != 0) {
1242                                         key_state |= Keys.Shift;
1243                                 }
1244                                 state = Win32GetKeyState(VirtualKeys.VK_CONTROL);
1245                                 if ((state & 0x8000) != 0) {
1246                                         key_state |= Keys.Control;
1247                                 }
1248
1249                                 state = Win32GetKeyState(VirtualKeys.VK_MENU);
1250                                 if ((state & 0x8000) != 0) {
1251                                         key_state |= Keys.Alt;
1252                                 }
1253
1254                                 return key_state;
1255                         }
1256                 }
1257
1258                 internal override MouseButtons MouseButtons {
1259                         get {
1260                                 return mouse_state;
1261                         }
1262                 }
1263
1264                 internal override Point MousePosition {
1265                         get {
1266                                 return mouse_position;
1267                         }
1268                 }
1269
1270                 internal override Size MouseHoverSize {
1271                         get {
1272                                 int     width = 4;
1273                                 int     height = 4;
1274
1275                                 Win32SystemParametersInfo(SPIAction.SPI_GETMOUSEHOVERWIDTH, 0, ref width, 0);
1276                                 Win32SystemParametersInfo(SPIAction.SPI_GETMOUSEHOVERWIDTH, 0, ref height, 0);
1277                                 return new Size(width, height);
1278                         }
1279                 }
1280
1281                 internal override int MouseHoverTime {
1282                         get {
1283                                 int time = 500;
1284
1285                                 Win32SystemParametersInfo(SPIAction.SPI_GETMOUSEHOVERTIME, 0, ref time, 0);
1286                                 return time;
1287                         }
1288                 }
1289
1290                 internal override int MouseWheelScrollDelta {
1291                         get {
1292                                 int delta = 120;
1293                                 Win32SystemParametersInfo(SPIAction.SPI_GETWHEELSCROLLLINES, 0, ref delta, 0);
1294                                 return delta;
1295                         }
1296                 }
1297                 
1298                 internal override int HorizontalScrollBarHeight {
1299                         get {
1300                                 return scroll_height;
1301                         }
1302                 }
1303
1304                 internal override bool UserClipWontExposeParent {
1305                         get {
1306                                 return false;
1307                         }
1308                 }
1309
1310
1311                 internal override int VerticalScrollBarWidth {
1312                         get {
1313                                 return scroll_width;
1314                         }
1315                 }
1316
1317                 internal override int MenuHeight {
1318                         get {
1319                                 return Win32GetSystemMetrics(SystemMetrics.SM_CYMENU);
1320                         }
1321                 }
1322
1323                 internal override Size Border3DSize {
1324                         get {
1325                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXEDGE),
1326                                         Win32GetSystemMetrics (SystemMetrics.SM_CYEDGE));
1327                         }
1328                 }
1329
1330                 internal override Size BorderSize {
1331                         get {
1332                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXBORDER),
1333                                         Win32GetSystemMetrics (SystemMetrics.SM_CYBORDER));
1334                         }
1335                 }
1336
1337                 internal override bool DropTarget {
1338                         get {
1339                                 return false;
1340                         }
1341
1342                         set {
1343                                 if (value) {
1344                                         //throw new NotImplementedException("Need to figure out D'n'D for Win32");
1345                                 }
1346                         }
1347                 }
1348
1349                 internal override Size CaptionButtonSize {
1350                         get {
1351                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXSIZE),
1352                                         Win32GetSystemMetrics (SystemMetrics.SM_CYSIZE));
1353                         }
1354                 }
1355
1356                 internal override int CaptionHeight {
1357                         get {
1358                                 return Win32GetSystemMetrics(SystemMetrics.SM_CYCAPTION);
1359                         }
1360                 }
1361
1362                 internal override Size CursorSize {
1363                         get {
1364                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR), Win32GetSystemMetrics(SystemMetrics.SM_CYCURSOR));
1365                         }
1366                 }
1367
1368                 internal override bool DragFullWindows {
1369                         get {
1370                                 int full = 0;
1371                                 Win32SystemParametersInfo (SPIAction.SPI_GETDRAGFULLWINDOWS, 0, ref full, 0);
1372                                 return (full != 0);
1373                         }
1374                 }
1375
1376                 internal override Size DragSize {
1377                         get {
1378                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXDRAG), Win32GetSystemMetrics(SystemMetrics.SM_CYDRAG));
1379                         }
1380                 }
1381
1382                 internal override Size DoubleClickSize {
1383                         get {
1384                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXDOUBLECLK),
1385                                         Win32GetSystemMetrics (SystemMetrics.SM_CYDOUBLECLK));
1386                         }
1387                 }
1388
1389                 internal override int DoubleClickTime {
1390                         get {
1391                                 return Win32GetDoubleClickTime ();
1392                         }
1393                 }
1394
1395                 internal override Size FixedFrameBorderSize {
1396                         get {
1397                                 return new Size (Win32GetSystemMetrics (SystemMetrics.SM_CXFIXEDFRAME),
1398                                         Win32GetSystemMetrics (SystemMetrics.SM_CYFIXEDFRAME));
1399                         }
1400                 }
1401
1402                 internal override Size FrameBorderSize { 
1403                         get {
1404                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXFRAME), Win32GetSystemMetrics(SystemMetrics.SM_CYFRAME));
1405                         }
1406                 }
1407
1408                 internal override Size IconSize {
1409                         get {
1410                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXICON), Win32GetSystemMetrics(SystemMetrics.SM_CYICON));
1411                         }
1412                 }
1413
1414                 internal override Size MaxWindowTrackSize {
1415                         get {
1416                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXMAXTRACK), Win32GetSystemMetrics(SystemMetrics.SM_CYMAXTRACK));
1417                         }
1418                 }
1419
1420                 internal override bool MenuAccessKeysUnderlined {
1421                         get {
1422                                 int underlined = 0;
1423                                 Win32SystemParametersInfo (SPIAction.SPI_GETKEYBOARDCUES, 0, ref underlined, 0);
1424                                 return (underlined != 0);
1425                         }
1426                 }
1427
1428                 internal override Size MinimizedWindowSize {
1429                         get {
1430                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXMINIMIZED), Win32GetSystemMetrics(SystemMetrics.SM_CYMINIMIZED));
1431                         }
1432                 }
1433
1434                 internal override Size MinimizedWindowSpacingSize {
1435                         get {
1436                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXMINSPACING), Win32GetSystemMetrics(SystemMetrics.SM_CYMINSPACING));
1437                         }
1438                 }
1439
1440                 internal override Size MinimumWindowSize {
1441                         get {
1442                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXMIN), Win32GetSystemMetrics(SystemMetrics.SM_CYMIN));
1443                         }
1444                 }
1445
1446                 internal override Size MinWindowTrackSize {
1447                         get {
1448                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXMINTRACK), Win32GetSystemMetrics(SystemMetrics.SM_CYMINTRACK));
1449                         }
1450                 }
1451
1452                 internal override Size SmallIconSize {
1453                         get {
1454                                 return new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXSMICON), Win32GetSystemMetrics(SystemMetrics.SM_CYSMICON));
1455                         }
1456                 }
1457
1458                 internal override int MouseButtonCount {
1459                         get {
1460                                 return Win32GetSystemMetrics(SystemMetrics.SM_CMOUSEBUTTONS);
1461                         }
1462                 }
1463
1464                 internal override bool MouseButtonsSwapped {
1465                         get {
1466                                 return Win32GetSystemMetrics(SystemMetrics.SM_SWAPBUTTON) != 0;
1467                         }
1468                 }
1469
1470                 internal override bool MouseWheelPresent {
1471                         get {
1472                                 return Win32GetSystemMetrics(SystemMetrics.SM_MOUSEWHEELPRESENT) != 0;
1473                         }
1474                 }
1475
1476                 internal override Rectangle VirtualScreen {
1477                         get {
1478                                 return new Rectangle(   Win32GetSystemMetrics(SystemMetrics.SM_XVIRTUALSCREEN), Win32GetSystemMetrics(SystemMetrics.SM_YVIRTUALSCREEN),
1479                                                         Win32GetSystemMetrics(SystemMetrics.SM_CXVIRTUALSCREEN), Win32GetSystemMetrics(SystemMetrics.SM_CYVIRTUALSCREEN));
1480                         }
1481                 }
1482
1483                 internal override Rectangle WorkingArea {
1484                         get {
1485                                 RECT    rect;
1486
1487                                 rect = new RECT();
1488                                 Win32SystemParametersInfo(SPIAction.SPI_GETWORKAREA, 0, ref rect, 0);
1489                                 return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
1490                                 //return new Rectangle(0, 0, Win32GetSystemMetrics(SystemMetrics.SM.SM_CXSCREEN), Win32GetSystemMetrics(SystemMetrics.SM_CYSCREEN));
1491                         }
1492                 }
1493
1494                 internal override bool ThemesEnabled {
1495                         get {
1496                                 return XplatUIWin32.themes_enabled;
1497                         }
1498                 }
1499  
1500
1501                 #endregion      // Static Properties
1502
1503                 #region Singleton Specific Code
1504                 public static XplatUIWin32 GetInstance() {
1505                         if (instance==null) {
1506                                 instance=new XplatUIWin32();
1507                         }
1508                         ref_count++;
1509                         return instance;
1510                 }
1511
1512                 public int Reference {
1513                         get {
1514                                 return ref_count;
1515                         }
1516                 }
1517                 #endregion
1518
1519                 #region Public Static Methods
1520                 internal override IntPtr InitializeDriver() {
1521                         return IntPtr.Zero;
1522                 }
1523
1524                 internal override void ShutdownDriver(IntPtr token) {
1525                         Console.WriteLine("XplatUIWin32 ShutdownDriver called");
1526                 }
1527
1528
1529                 internal void Version() {
1530                         Console.WriteLine("Xplat version $revision: $");
1531                 }
1532
1533                 internal override void AudibleAlert() {
1534                         Win32PlaySound("Default", IntPtr.Zero, SndFlags.SND_ALIAS | SndFlags.SND_ASYNC | SndFlags.SND_NOSTOP | SndFlags.SND_NOWAIT);
1535                 }
1536
1537                 internal override void GetDisplaySize(out Size size) {
1538                         RECT    rect;
1539
1540                         Win32GetWindowRect(Win32GetDesktopWindow(), out rect);
1541
1542                         size = new Size(rect.right - rect.left, rect.bottom - rect.top);
1543                 }
1544
1545                 internal override void EnableThemes() {
1546                         themes_enabled=true;
1547                 }
1548
1549                 internal override IntPtr CreateWindow(CreateParams cp) {
1550                         IntPtr  WindowHandle;
1551                         IntPtr  ParentHandle;
1552                         Hwnd    hwnd;
1553
1554                         hwnd = new Hwnd();
1555
1556                         ParentHandle=cp.Parent;
1557
1558                         if ((ParentHandle==IntPtr.Zero) && (cp.Style & (int)(WindowStyles.WS_CHILD))!=0) {
1559                                 // We need to use our foster parent window until this poor child gets it's parent assigned
1560                                 ParentHandle = FosterParent;
1561                         }
1562
1563                         if ( ((cp.Style & (int)(WindowStyles.WS_CHILD | WindowStyles.WS_POPUP))==0) && ((cp.ExStyle & (int)WindowExStyles.WS_EX_APPWINDOW) == 0)) {
1564                                 // If we want to be hidden from the taskbar we need to be 'owned' by 
1565                                 // something not on the taskbar. FosterParent is just that
1566                                 ParentHandle = FosterParent;
1567                         }
1568
1569                         Point location;
1570                         if (cp.HasWindowManager) {
1571                                 location = Hwnd.GetNextStackedFormLocation (cp, Hwnd.ObjectFromHandle (cp.Parent));
1572                         } else {
1573                                 location = new Point (cp.X, cp.Y);
1574                         }
1575
1576                         string class_name = RegisterWindowClass (cp.ClassStyle);
1577                         HwndCreating = hwnd;
1578
1579                         WindowHandle = Win32CreateWindow (cp.WindowExStyle, class_name, cp.Caption, cp.WindowStyle, location.X, location.Y, cp.Width, cp.Height, ParentHandle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
1580
1581                         HwndCreating = null;
1582
1583                         if (WindowHandle==IntPtr.Zero) {
1584                                 uint error = Win32GetLastError();
1585
1586                                 Win32MessageBox(IntPtr.Zero, "Error : " + error.ToString(), "Failed to create window, class '"+cp.ClassName+"'", 0);
1587                         }
1588
1589                         hwnd.ClientWindow = WindowHandle;
1590
1591                         Win32SetWindowLong(WindowHandle, WindowLong.GWL_USERDATA, (uint)ThemeEngine.Current.DefaultControlBackColor.ToArgb());
1592
1593                         return WindowHandle;
1594                 }
1595
1596                 internal override IntPtr CreateWindow(IntPtr Parent, int X, int Y, int Width, int Height) {
1597                         CreateParams create_params = new CreateParams();
1598
1599                         create_params.Caption = "";
1600                         create_params.X = X;
1601                         create_params.Y = Y;
1602                         create_params.Width = Width;
1603                         create_params.Height = Height;
1604
1605                         create_params.ClassName=XplatUI.DefaultClassName;
1606                         create_params.ClassStyle = 0;
1607                         create_params.ExStyle=0;
1608                         create_params.Parent=IntPtr.Zero;
1609                         create_params.Param=0;
1610
1611                         return CreateWindow(create_params);
1612                 }
1613
1614                 internal override void DestroyWindow(IntPtr handle) {
1615                         Hwnd    hwnd;
1616
1617                         hwnd = Hwnd.ObjectFromHandle(handle);
1618                         Win32DestroyWindow(handle);
1619                         hwnd.Dispose();
1620                         return;
1621                 }
1622
1623                 internal override void SetWindowMinMax(IntPtr handle, Rectangle maximized, Size min, Size max) {
1624                         // We do nothing, Form has to handle WM_GETMINMAXINFO
1625                 }
1626
1627
1628                 internal override FormWindowState GetWindowState(IntPtr handle) {
1629                         uint style;
1630
1631                         style = Win32GetWindowLong(handle, WindowLong.GWL_STYLE);
1632                         if ((style & (uint)WindowStyles.WS_MAXIMIZE) != 0) {
1633                                 return FormWindowState.Maximized;
1634                         } else if ((style & (uint)WindowStyles.WS_MINIMIZE) != 0) {
1635                                 return FormWindowState.Minimized;
1636                         }
1637                         return FormWindowState.Normal;
1638                 }
1639
1640                 internal override void SetWindowState(IntPtr hwnd, FormWindowState state) {
1641                         switch(state) {
1642                                 case FormWindowState.Normal: {
1643                                         Win32ShowWindow(hwnd, WindowPlacementFlags.SW_RESTORE);
1644                                         return;
1645                                 }
1646
1647                                 case FormWindowState.Minimized: {
1648                                         Win32ShowWindow(hwnd, WindowPlacementFlags.SW_MINIMIZE);
1649                                         return;
1650                                 }
1651
1652                                 case FormWindowState.Maximized: {
1653                                         Win32ShowWindow(hwnd, WindowPlacementFlags.SW_MAXIMIZE);
1654                                         return;
1655                                 }
1656                         }
1657                 }
1658
1659                 internal override void SetWindowStyle(IntPtr handle, CreateParams cp) {
1660
1661                         Win32SetWindowLong(handle, WindowLong.GWL_STYLE, (uint)cp.Style);
1662                         Win32SetWindowLong(handle, WindowLong.GWL_EXSTYLE, (uint)cp.ExStyle);
1663
1664                         if ((cp.ExStyle & (int) WindowExStyles.WS_EX_TOOLWINDOW) > 0 || 
1665                                 ((cp.WindowStyle & (WindowStyles.WS_CAPTION)) != WindowStyles.WS_CAPTION && cp.control is Form))
1666                                 XplatUI.RequestNCRecalc (handle);
1667                 }
1668
1669                 internal override double GetWindowTransparency(IntPtr handle)
1670                 {
1671                         LayeredWindowAttributes lwa;
1672                         COLORREF clrRef;
1673                         byte alpha;
1674
1675                         if (0 == Win32GetLayeredWindowAttributes (handle, out clrRef, out alpha, out lwa))
1676                                 return 1.0;
1677
1678                         return ((double)alpha) / 255.0;
1679                 }
1680
1681                 internal override void SetWindowTransparency(IntPtr handle, double transparency, Color key) {
1682                         LayeredWindowAttributes lwa = LayeredWindowAttributes.LWA_ALPHA;
1683                         byte opacity = (byte)(transparency*255);
1684                         COLORREF clrRef = new COLORREF();
1685                         if (key != Color.Empty) {
1686                                 clrRef.R = key.R;
1687                                 clrRef.G = key.G;
1688                                 clrRef.B = key.B;
1689                                 lwa = (LayeredWindowAttributes)( (int)lwa | (int)LayeredWindowAttributes.LWA_COLORKEY );
1690                         }
1691                         RECT rc;
1692                         rc.right = 1000;
1693                         rc.bottom = 1000;
1694                         Win32SetLayeredWindowAttributes(handle, clrRef, opacity, lwa);
1695                 }
1696
1697                 TransparencySupport support;
1698                 bool queried_transparency_support;
1699                 internal override TransparencySupport SupportsTransparency() {
1700                         if (queried_transparency_support)
1701                                 return support;
1702
1703                         bool flag;
1704                         support = TransparencySupport.None;
1705
1706                         flag = true;
1707                         try {
1708                                 Win32SetLayeredWindowAttributes (IntPtr.Zero, new COLORREF (), 255, LayeredWindowAttributes.LWA_ALPHA);
1709                         }
1710                         catch (EntryPointNotFoundException) { flag = false; }
1711                         catch { /* swallow everything else */ }
1712
1713                         if (flag) support |= TransparencySupport.Set;
1714
1715                         flag = true;
1716                         try {
1717                                 LayeredWindowAttributes lwa;
1718                                 COLORREF clrRef;
1719                                 byte alpha;
1720
1721                                 Win32GetLayeredWindowAttributes (IntPtr.Zero, out clrRef, out alpha, out lwa);
1722                         }
1723                         catch (EntryPointNotFoundException) { flag = false; }
1724                         catch { /* swallow everything else */ }
1725
1726                         if (flag) support |= TransparencySupport.Get;
1727
1728                         queried_transparency_support = true;
1729                         return support;
1730                 }
1731
1732                 internal override void UpdateWindow(IntPtr handle) {
1733                         Win32UpdateWindow(handle);
1734                 }
1735
1736                 internal override PaintEventArgs PaintEventStart(IntPtr handle, bool client) {
1737                         IntPtr          hdc;
1738                         PAINTSTRUCT     ps;
1739                         PaintEventArgs  paint_event;
1740                         RECT            rect;
1741                         Rectangle       clip_rect;
1742                         Hwnd            hwnd;
1743
1744                         clip_rect = new Rectangle();
1745                         rect = new RECT();
1746                         ps = new PAINTSTRUCT();
1747
1748                         hwnd = Hwnd.ObjectFromHandle(handle);
1749
1750                         if (client) {
1751                                 if (Win32GetUpdateRect(handle, ref rect, false)) {
1752                                         hdc = Win32BeginPaint(handle, ref ps);
1753
1754                                         hwnd.drawing_stack.Push (ps);
1755
1756                                         clip_rect = new Rectangle(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right-ps.rcPaint.left, ps.rcPaint.bottom-ps.rcPaint.top);
1757                                 } else {
1758                                         hdc = Win32GetDC(handle);
1759                                         // FIXME: Add the DC to internal list
1760
1761                                         hwnd.drawing_stack.Push (null);
1762
1763                                         clip_rect = new Rectangle(rect.top, rect.left, rect.right-rect.left, rect.bottom-rect.top);
1764                                 }
1765                         } else {
1766                                 hdc = Win32GetWindowDC (handle);
1767
1768                                 hwnd.drawing_stack.Push (hdc);
1769
1770                                 // HACK this in for now
1771                                 Win32GetWindowRect (handle, out rect);
1772                                 clip_rect = new Rectangle(0, 0, rect.right-rect.left, rect.bottom-rect.top);
1773                         }
1774
1775                         Graphics dc = Graphics.FromHdc(hdc);
1776                         hwnd.drawing_stack.Push (dc);
1777
1778                         paint_event = new PaintEventArgs(dc, clip_rect);
1779
1780                         return paint_event;
1781                 }
1782
1783                 internal override void PaintEventEnd(IntPtr handle, bool client) {
1784                         Hwnd            hwnd;
1785
1786                         hwnd = Hwnd.ObjectFromHandle(handle);
1787
1788                         Graphics dc = (Graphics)hwnd.drawing_stack.Pop();
1789                         dc.Dispose ();
1790
1791                         if (client) {
1792                                 object o = hwnd.drawing_stack.Pop();
1793                                 if (o != null) {
1794                                         PAINTSTRUCT ps = (PAINTSTRUCT)o;
1795                                         Win32EndPaint(handle, ref ps);
1796                                 }
1797                         } else {
1798                                 IntPtr hdc = (IntPtr)hwnd.drawing_stack.Pop();
1799                                 Win32ReleaseDC(handle, hdc);
1800                         }
1801                 }
1802
1803
1804                 internal override void SetWindowPos(IntPtr handle, int x, int y, int width, int height) {
1805                         Win32MoveWindow(handle, x, y, width, height, true);
1806                         return;
1807                 }
1808
1809                 internal override void GetWindowPos(IntPtr handle, bool is_toplevel, out int x, out int y, out int width, out int height, out int client_width, out int client_height) {
1810                         IntPtr  parent;
1811                         RECT    rect;
1812                         POINT   pt;
1813
1814                         Win32GetWindowRect(handle, out rect);
1815                         width = rect.right - rect.left;
1816                         height = rect.bottom - rect.top;
1817
1818                         pt.x=rect.left;
1819                         pt.y=rect.top;
1820
1821                         parent = Win32GetAncestor (handle, AncestorType.GA_PARENT);
1822                         if (parent != IntPtr.Zero && parent != Win32GetDesktopWindow ())
1823                                 Win32ScreenToClient(parent, ref pt);
1824
1825                         x = pt.x;
1826                         y = pt.y;
1827
1828                         Win32GetClientRect(handle, out rect);
1829                         client_width = rect.right - rect.left;
1830                         client_height = rect.bottom - rect.top;
1831                         return;
1832                 }
1833
1834                 internal override void Activate(IntPtr handle) {
1835                         Win32SetActiveWindow(handle);
1836                 }
1837
1838                 internal override void Invalidate(IntPtr handle, Rectangle rc, bool clear) {
1839                         RECT rect;
1840
1841                         rect.left=rc.Left;
1842                         rect.top=rc.Top;
1843                         rect.right=rc.Right;
1844                         rect.bottom=rc.Bottom;
1845                         Win32InvalidateRect(handle, ref rect, clear);
1846                 }
1847
1848
1849                 internal override void InvalidateNC (IntPtr handle)
1850                 {
1851                         // found this gem at
1852                         // http://www.dotnet247.com/247reference/msgs/58/292037.aspx
1853                         Win32SetWindowPos(handle, IntPtr.Zero,
1854                                           0, 0, 0, 0,
1855                                           SetWindowPosFlags.SWP_NOMOVE |
1856                                           SetWindowPosFlags.SWP_NOSIZE |
1857                                           SetWindowPosFlags.SWP_NOZORDER |
1858                                           SetWindowPosFlags.SWP_NOACTIVATE |
1859                                           SetWindowPosFlags.SWP_DRAWFRAME);
1860                 }
1861
1862                 private IntPtr InternalWndProc (IntPtr hWnd, Msg msg, IntPtr wParam, IntPtr lParam)
1863                 {
1864                         if (HwndCreating != null && HwndCreating.ClientWindow == IntPtr.Zero)
1865                                 HwndCreating.ClientWindow = hWnd;
1866                         return NativeWindow.WndProc (hWnd, msg, wParam, lParam);
1867                 }
1868
1869                 internal override IntPtr DefWndProc(ref Message msg) {
1870                         msg.Result=Win32DefWindowProc(msg.HWnd, (Msg)msg.Msg, msg.WParam, msg.LParam);
1871                         return msg.Result;
1872                 }
1873
1874                 internal override void HandleException(Exception e) {
1875                         StackTrace st = new StackTrace(e);
1876                         Win32MessageBox(IntPtr.Zero, e.Message+st.ToString(), "Exception", 0);
1877                         Console.WriteLine("{0}{1}", e.Message, st.ToString());
1878                 }
1879
1880                 internal override void DoEvents() {
1881                         MSG msg = new MSG();
1882
1883                         if (override_cursor != IntPtr.Zero) {
1884                                 Cursor.Current = null;
1885                         }
1886
1887                         while (GetMessage(ref msg, IntPtr.Zero, 0, 0, false)) {
1888                                 XplatUI.TranslateMessage(ref msg);
1889                                 XplatUI.DispatchMessage(ref msg);
1890                         }
1891                 }
1892
1893                 internal override bool PeekMessage(Object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags) {
1894                         return Win32PeekMessage(ref msg, hWnd, wFilterMin, wFilterMax, flags);
1895                 }
1896
1897                 internal override void PostQuitMessage(int exitCode) {
1898                         Win32PostQuitMessage(exitCode);
1899                 }
1900
1901                 internal override void RequestAdditionalWM_NCMessages(IntPtr hwnd, bool hover, bool leave)
1902                 {
1903                         if (wm_nc_registered == null)
1904                                 wm_nc_registered = new Hashtable ();
1905                                 
1906                         TMEFlags flags = TMEFlags.TME_NONCLIENT;
1907                         if (hover)
1908                                 flags |= TMEFlags.TME_HOVER;
1909                         if (leave)
1910                                 flags |= TMEFlags.TME_LEAVE;
1911
1912                         if (flags == TMEFlags.TME_NONCLIENT) {
1913                                 if (wm_nc_registered.Contains (hwnd)) {
1914                                         wm_nc_registered.Remove (hwnd);
1915                                 }
1916                         } else {
1917                                 if (!wm_nc_registered.Contains (hwnd)) {
1918                                         wm_nc_registered.Add (hwnd, flags);
1919                                 } else {
1920                                         wm_nc_registered [hwnd] = flags;
1921                                 }
1922                         }
1923                 }
1924
1925                 internal override void RequestNCRecalc(IntPtr handle) {
1926                         Win32SetWindowPos(handle, IntPtr.Zero, 0, 0, 0, 0, SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE);
1927                 }
1928
1929                 internal override void ResetMouseHover(IntPtr handle) {
1930                         TRACKMOUSEEVENT tme;
1931
1932                         tme = new TRACKMOUSEEVENT();
1933                         tme.size = Marshal.SizeOf(tme);
1934                         tme.hWnd = handle;
1935                         tme.dwFlags = TMEFlags.TME_LEAVE | TMEFlags.TME_HOVER;
1936                         Win32TrackMouseEvent(ref tme);
1937                 }
1938
1939
1940                 internal override bool GetMessage(Object queue_id, ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax) {
1941                         return GetMessage(ref msg, hWnd, wFilterMin, wFilterMax, true);
1942                 }
1943
1944                 private bool GetMessage(ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, bool blocking) {
1945                         bool            result;
1946
1947                         msg.refobject = 0;
1948                         if (RetrieveMessage(ref msg)) {
1949                                 return true;
1950                         }
1951
1952                         if (blocking) {
1953                                 result = Win32GetMessage(ref msg, hWnd, wFilterMin, wFilterMax);
1954                         } else {
1955                                 result = Win32PeekMessage(ref msg, hWnd, wFilterMin, wFilterMax, (uint)PeekMessageFlags.PM_REMOVE);
1956                                 if (!result) {
1957                                         return false;
1958                                 }
1959                         }
1960
1961                         // We need to fake WM_MOUSE_ENTER
1962                         switch (msg.message) {
1963                                 case Msg.WM_LBUTTONDOWN: {
1964                                         mouse_state |= MouseButtons.Left;
1965                                         break;
1966                                 }
1967
1968                                 case Msg.WM_MBUTTONDOWN: {
1969                                         mouse_state |= MouseButtons.Middle;
1970                                         break;
1971                                 }
1972
1973                                 case Msg.WM_RBUTTONDOWN: {
1974                                         mouse_state |= MouseButtons.Right;
1975                                         break;
1976                                 }
1977
1978                                 case Msg.WM_LBUTTONUP: {
1979                                         mouse_state &= ~MouseButtons.Left;
1980                                         break;
1981                                 }
1982
1983                                 case Msg.WM_MBUTTONUP: {
1984                                         mouse_state &= ~MouseButtons.Middle;
1985                                         break;
1986                                 }
1987
1988                                 case Msg.WM_RBUTTONUP: {
1989                                         mouse_state &= ~MouseButtons.Right;
1990                                         break;
1991                                 }
1992
1993                                 case Msg.WM_ASYNC_MESSAGE: {
1994                                         XplatUIDriverSupport.ExecuteClientMessage((GCHandle)msg.lParam);
1995                                         break;
1996                                 }
1997
1998                                 case Msg.WM_MOUSEMOVE: {
1999                                         if (msg.hwnd != prev_mouse_hwnd) {
2000                                                 TRACKMOUSEEVENT tme;
2001
2002                                                 // The current message will be sent out next time around
2003                                                 StoreMessage(ref msg);
2004
2005                                                 // This is the message we want to send at this point
2006                                                 msg.message = Msg.WM_MOUSE_ENTER;
2007
2008                                                 prev_mouse_hwnd = msg.hwnd;
2009
2010                                                 tme = new TRACKMOUSEEVENT();
2011                                                 tme.size = Marshal.SizeOf(tme);
2012                                                 tme.hWnd = msg.hwnd;
2013                                                 tme.dwFlags = TMEFlags.TME_LEAVE | TMEFlags.TME_HOVER;
2014                                                 Win32TrackMouseEvent(ref tme);
2015                                                 return result;
2016                                         }
2017                                         break;
2018                                 }
2019
2020                                 case Msg.WM_NCMOUSEMOVE: {
2021                                         if (wm_nc_registered == null || !wm_nc_registered.Contains (msg.hwnd))
2022                                                 break;
2023                                                 
2024                                         TRACKMOUSEEVENT tme;
2025
2026                                         tme = new TRACKMOUSEEVENT ();
2027                                         tme.size = Marshal.SizeOf(tme);
2028                                         tme.hWnd = msg.hwnd;
2029                                         tme.dwFlags = (TMEFlags)wm_nc_registered[msg.hwnd];
2030                                         Win32TrackMouseEvent (ref tme);
2031                                         return result;
2032                                 }
2033
2034                                 case Msg.WM_DROPFILES: {
2035                                         return Win32DnD.HandleWMDropFiles(ref msg);
2036                                 }
2037
2038                                 case Msg.WM_MOUSELEAVE: {
2039                                         prev_mouse_hwnd = IntPtr.Zero;
2040                                         break;
2041                                 }
2042
2043                                 case Msg.WM_TIMER: {
2044                                         Timer timer=(Timer)timer_list[(int)msg.wParam];
2045
2046                                         if (timer != null) {
2047                                                 timer.FireTick();
2048                                         }
2049                                         break;
2050                                 }
2051                         }
2052
2053                         return result;
2054                 }
2055
2056                 internal override bool TranslateMessage(ref MSG msg) {
2057                         return Win32TranslateMessage(ref msg);
2058                 }
2059
2060                 internal override IntPtr DispatchMessage(ref MSG msg) {
2061                         return Win32DispatchMessage(ref msg);
2062                 }
2063
2064                 internal override bool SetZOrder(IntPtr hWnd, IntPtr AfterhWnd, bool Top, bool Bottom) {
2065                         if (Top) {
2066                                 Win32SetWindowPos(hWnd, SetWindowPosZOrder.HWND_TOP, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE);
2067                                 return true;
2068                         } else if (!Bottom) {
2069                                 Win32SetWindowPos(hWnd, AfterhWnd, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE);
2070                         } else {
2071                                 Win32SetWindowPos(hWnd, (IntPtr)SetWindowPosZOrder.HWND_BOTTOM, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE);
2072                                 return true;
2073                         }
2074                         return false;
2075                 }
2076
2077                 internal override bool SetTopmost(IntPtr hWnd, bool Enabled) {
2078                         if (Enabled) {
2079                                 Win32SetWindowPos(hWnd, SetWindowPosZOrder.HWND_TOPMOST, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE);
2080                                 return true;
2081                         } else {
2082                                 Win32SetWindowPos(hWnd, SetWindowPosZOrder.HWND_NOTOPMOST, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE);
2083                                 return true;
2084                         }
2085                 }
2086                 
2087                 internal override bool SetOwner(IntPtr hWnd, IntPtr hWndOwner) {
2088                         Win32SetWindowLong(hWnd, WindowLong.GWL_HWNDPARENT, (uint) hWndOwner);
2089                         return true;
2090                 }
2091
2092                 internal override bool Text(IntPtr handle, string text) {
2093                         Win32SetWindowText(handle, text);
2094                         return true;
2095                 }
2096
2097                 internal override bool GetText(IntPtr handle, out string text) {
2098                         StringBuilder sb;
2099
2100                         sb = new StringBuilder(256);
2101                         Win32GetWindowText(handle, sb, sb.Capacity);
2102                         text = sb.ToString();
2103                         return true;
2104                 }
2105
2106                 internal override bool SetVisible (IntPtr handle, bool visible, bool activate)
2107                 {
2108                         if (visible) {
2109                                 Control c = Control.FromHandle (handle);
2110                                 if (c is Form) {
2111                                         Form f;
2112
2113                                         f = (Form)Control.FromHandle (handle);
2114                                         WindowPlacementFlags flags = WindowPlacementFlags.SW_SHOWNORMAL;
2115                                         switch (f.WindowState) {
2116                                                 case FormWindowState.Normal: flags = WindowPlacementFlags.SW_SHOWNORMAL; break;
2117                                                 case FormWindowState.Minimized: flags = WindowPlacementFlags.SW_MINIMIZE; break;
2118                                                 case FormWindowState.Maximized: flags = WindowPlacementFlags.SW_MAXIMIZE; break;
2119                                         }
2120                                         
2121                                         if (!f.ActivateOnShow)
2122                                                 flags = WindowPlacementFlags.SW_SHOWNOACTIVATE;
2123                                                 
2124                                         Win32ShowWindow (handle, flags);
2125                                 }
2126                                 else {
2127                                         if (c.ActivateOnShow)
2128                                                 Win32ShowWindow (handle, WindowPlacementFlags.SW_SHOWNORMAL);
2129                                         else
2130                                                 Win32ShowWindow (handle, WindowPlacementFlags.SW_SHOWNOACTIVATE);
2131                                 }
2132                         }
2133                         else {
2134                                 Win32ShowWindow (handle, WindowPlacementFlags.SW_HIDE);
2135                         }
2136                         return true;
2137                 }
2138
2139                 internal override bool IsEnabled(IntPtr handle) {
2140                         return IsWindowEnabled (handle);
2141                 }
2142                 
2143                 internal override bool IsVisible(IntPtr handle) {
2144                         return IsWindowVisible (handle);
2145                 }
2146
2147                 internal override IntPtr SetParent(IntPtr handle, IntPtr parent) {
2148                         Control c = Control.FromHandle (handle);
2149                         if (parent == IntPtr.Zero) {
2150                                 if (!(c is Form)) {
2151                                         Win32ShowWindow(handle, WindowPlacementFlags.SW_HIDE);
2152                                 }
2153                         } else {
2154                                 if (!(c is Form)) {
2155                                         SetVisible (handle, c.is_visible, true);
2156                                 }
2157                         }       
2158                         // The Win32SetParent is lame, it can very well move the window
2159                         // ref: http://groups.google.com/group/microsoft.public.vb.winapi/browse_thread/thread/1b82ccc54231ecee/afa82835bfc0422a%23afa82835bfc0422a
2160                         // Here we save the position before changing the parent, and if it has changed afterwards restore it.
2161                         // Another possibility would be to intercept WM_WINDOWPOSCHANGING and restore the coords there, but this would require plumbing in weird places
2162                         // (either inside Control or add handling to InternalWndProc)
2163                         // We also need to remove WS_CHILD if making the window parent-less, and add it if we're parenting it.
2164                         RECT rect, rect2;
2165                         IntPtr result;
2166                         WindowStyles style, new_style;
2167                         
2168                         Win32GetWindowRect (handle, out rect);
2169                         style = (WindowStyles) Win32GetWindowLong (handle, WindowLong.GWL_STYLE);
2170                         
2171                         if (parent == IntPtr.Zero) {
2172                                 new_style = style & ~WindowStyles.WS_CHILD;
2173                                 result = Win32SetParent (handle, FosterParent);
2174                         } else {
2175                                 new_style = style | WindowStyles.WS_CHILD;
2176                                 result = Win32SetParent (handle, parent);
2177                         }
2178                         if (style != new_style && c is Form) {
2179                                 Win32SetWindowLong (handle, WindowLong.GWL_STYLE, (uint) new_style);
2180                         }
2181                         Win32GetWindowRect (handle, out rect2);
2182                         if (rect.top != rect2.top && rect.left != rect2.left && c is Form) {
2183                                 Win32SetWindowPos (handle, IntPtr.Zero, rect.top, rect.left, rect.Width, rect.Height, SetWindowPosFlags.SWP_NOZORDER |  SetWindowPosFlags.SWP_NOREDRAW | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOENDSCHANGING | SetWindowPosFlags.SWP_NOACTIVATE);
2184                         }
2185                         return result;
2186                 }
2187
2188                 // If we ever start using this, we should probably replace FosterParent with IntPtr.Zero
2189                 internal override IntPtr GetParent(IntPtr handle) {
2190                         return Win32GetParent(handle);
2191                 }
2192
2193                 internal override void GrabWindow(IntPtr hWnd, IntPtr ConfineToHwnd) {
2194                         grab_hwnd = hWnd;
2195                         Win32SetCapture(hWnd);
2196                         
2197                         if (ConfineToHwnd != IntPtr.Zero) {
2198                                 RECT window_rect;
2199                                 Win32GetWindowRect (ConfineToHwnd, out window_rect);
2200                                 Win32GetClipCursor (out clipped_cursor_rect);
2201                                 Win32ClipCursor (ref window_rect);
2202                         }
2203                 }
2204
2205                 internal override void GrabInfo(out IntPtr hWnd, out bool GrabConfined, out Rectangle GrabArea) {
2206                         hWnd = grab_hwnd;
2207                         GrabConfined = grab_confined;
2208                         GrabArea = grab_area;
2209                 }
2210
2211                 internal override void UngrabWindow(IntPtr hWnd) {
2212                         if (!(clipped_cursor_rect.top == 0 && clipped_cursor_rect.bottom == 0 && clipped_cursor_rect.left == 0 && clipped_cursor_rect.right == 0)) {
2213                                 Win32ClipCursor (ref clipped_cursor_rect);
2214                                 clipped_cursor_rect = new RECT ();
2215                         }
2216                         
2217                         Win32ReleaseCapture();
2218                         grab_hwnd = IntPtr.Zero;
2219                 }
2220
2221                 internal override bool CalculateWindowRect(ref Rectangle ClientRect, CreateParams cp, Menu menu, out Rectangle WindowRect) {
2222                         RECT    rect;
2223
2224                         rect.left=ClientRect.Left;
2225                         rect.top=ClientRect.Top;
2226                         rect.right=ClientRect.Right;
2227                         rect.bottom=ClientRect.Bottom;
2228
2229                         if (!Win32AdjustWindowRectEx(ref rect, cp.Style, menu != null, cp.ExStyle)) {
2230                                 WindowRect = new Rectangle(ClientRect.Left, ClientRect.Top, ClientRect.Width, ClientRect.Height);
2231                                 return false;
2232                         }
2233
2234                         WindowRect = new Rectangle(rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top);
2235                         return true;
2236                 }
2237
2238                 internal override void SetCursor(IntPtr window, IntPtr cursor) {
2239                         Win32SetCursor(cursor);
2240                         return;
2241                 }
2242
2243                 internal override void ShowCursor(bool show) {
2244                         Win32ShowCursor(show);
2245                 }
2246
2247                 internal override void OverrideCursor(IntPtr cursor) {
2248                         Win32SetCursor(cursor);
2249                 }
2250
2251                 internal override IntPtr DefineCursor(Bitmap bitmap, Bitmap mask, Color cursor_pixel, Color mask_pixel, int xHotSpot, int yHotSpot) {
2252                         IntPtr  cursor;
2253                         Bitmap  cursor_bitmap;
2254                         Bitmap  cursor_mask;
2255                         Byte[]  cursor_bits;
2256                         Byte[]  mask_bits;
2257                         Color   pixel;
2258                         int     width;
2259                         int     height;
2260
2261                         // Win32 only allows creation cursors of a certain size
2262                         if ((bitmap.Width != Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR)) || (bitmap.Width != Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR))) {
2263                                 cursor_bitmap = new Bitmap(bitmap, new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR), Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR)));
2264                                 cursor_mask = new Bitmap(mask, new Size(Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR), Win32GetSystemMetrics(SystemMetrics.SM_CXCURSOR)));
2265                         } else {
2266                                 cursor_bitmap = bitmap;
2267                                 cursor_mask = mask;
2268                         }
2269
2270                         width = cursor_bitmap.Width;
2271                         height = cursor_bitmap.Height;
2272
2273                         cursor_bits = new Byte[(width / 8) * height];
2274                         mask_bits = new Byte[(width / 8) * height];
2275
2276                         for (int y = 0; y < height; y++) {
2277                                 for (int x = 0; x < width; x++) {
2278                                         pixel = cursor_bitmap.GetPixel(x, y);
2279
2280                                         if (pixel == cursor_pixel) {
2281                                                 cursor_bits[y * width / 8 + x / 8] |= (byte)(0x80 >> (x % 8));
2282                                         }
2283
2284                                         pixel = cursor_mask.GetPixel(x, y);
2285
2286                                         if (pixel == mask_pixel) {
2287                                                 mask_bits[y * width / 8 + x / 8] |= (byte)(0x80 >> (x % 8));
2288                                         }
2289                                 }
2290                         }
2291
2292                         cursor = Win32CreateCursor(IntPtr.Zero, xHotSpot, yHotSpot, width, height, mask_bits, cursor_bits);
2293
2294                         return cursor;
2295                 }
2296
2297                 internal override Bitmap DefineStdCursorBitmap (StdCursor id)
2298                 {
2299                         // We load the cursor, create a bitmap, draw the cursor onto the bitmap and return the bitmap.
2300                         IntPtr cursor = DefineStdCursor (id);
2301                         // Windows only have one possible cursor size!
2302                         int width = Win32GetSystemMetrics (SystemMetrics.SM_CXCURSOR);
2303                         int height = Win32GetSystemMetrics (SystemMetrics.SM_CYCURSOR);
2304                         Bitmap bmp = new Bitmap (width, height);
2305                         Graphics gc = Graphics.FromImage (bmp);
2306                         IntPtr hdc = gc.GetHdc ();
2307                         Win32DrawIcon (hdc, 0, 0, cursor);
2308                         gc.ReleaseHdc (hdc);
2309                         gc.Dispose ();
2310                         return bmp;
2311                 }
2312
2313                 [MonoTODO("Define the missing cursors")]
2314                 internal override IntPtr DefineStdCursor(StdCursor id) {
2315                         switch(id) {
2316                                 case StdCursor.AppStarting:     return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_APPSTARTING);
2317                                 case StdCursor.Arrow:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);
2318                                 case StdCursor.Cross:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_CROSS);
2319                                 case StdCursor.Default:         return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);
2320                                 case StdCursor.Hand:            return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_HAND);
2321                                 case StdCursor.Help:            return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_HELP);
2322                                 case StdCursor.HSplit:          return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2323                                 case StdCursor.IBeam:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_IBEAM);
2324                                 case StdCursor.No:              return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_NO);
2325                                 case StdCursor.NoMove2D:        return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2326                                 case StdCursor.NoMoveHoriz:     return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2327                                 case StdCursor.NoMoveVert:      return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2328                                 case StdCursor.PanEast:         return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2329                                 case StdCursor.PanNE:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2330                                 case StdCursor.PanNorth:        return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2331                                 case StdCursor.PanNW:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2332                                 case StdCursor.PanSE:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2333                                 case StdCursor.PanSouth:        return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2334                                 case StdCursor.PanSW:           return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2335                                 case StdCursor.PanWest:         return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2336                                 case StdCursor.SizeAll:         return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_SIZEALL);
2337                                 case StdCursor.SizeNESW:        return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_SIZENESW);
2338                                 case StdCursor.SizeNS:          return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_SIZENS);
2339                                 case StdCursor.SizeNWSE:        return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_SIZENWSE);
2340                                 case StdCursor.SizeWE:          return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_SIZEWE);
2341                                 case StdCursor.UpArrow:         return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_UPARROW);
2342                                 case StdCursor.VSplit:          return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_ARROW);          // FIXME
2343                                 case StdCursor.WaitCursor:      return Win32LoadCursor(IntPtr.Zero, LoadCursorType.IDC_WAIT);
2344                         }
2345                         throw new NotImplementedException ();
2346                 }
2347
2348                 internal override void DestroyCursor(IntPtr cursor) {
2349                         if ((cursor.ToInt32() < (int)LoadCursorType.First) || (cursor.ToInt32() > (int)LoadCursorType.Last)) {
2350                                 Win32DestroyCursor(cursor);
2351                         }
2352                 }
2353
2354                 [MonoTODO]
2355                 internal override void GetCursorInfo(IntPtr cursor, out int width, out int height, out int hotspot_x, out int hotspot_y) {
2356                         width = 20;
2357                         height = 20;
2358                         hotspot_x = 0;
2359                         hotspot_y = 0;
2360                 }
2361
2362                 internal override void SetCursorPos(IntPtr handle, int x, int y) {
2363                         Win32SetCursorPos(x, y);
2364                 }
2365
2366                 internal override Region GetClipRegion(IntPtr hwnd) {
2367                         Region region;
2368
2369                         region = new Region();
2370
2371                         Win32GetWindowRgn(hwnd, region.GetHrgn(Graphics.FromHwnd(hwnd)));
2372
2373                         return region;
2374                 }
2375
2376                 internal override void SetClipRegion(IntPtr hwnd, Region region) {
2377                         Win32SetWindowRgn(hwnd, region.GetHrgn(Graphics.FromHwnd(hwnd)), true);
2378                 }
2379
2380                 internal override void EnableWindow(IntPtr handle, bool Enable) {
2381                         Win32EnableWindow(handle, Enable);
2382                 }
2383
2384                 internal override void EndLoop(System.Threading.Thread thread) {
2385                         // Nothing to do
2386                 }
2387
2388                 internal override object StartLoop(System.Threading.Thread thread) {
2389                         return null;
2390                 }
2391
2392                 internal override void SetModal(IntPtr handle, bool Modal) {
2393                         // we do nothing on Win32
2394                 }
2395
2396                 internal override void GetCursorPos(IntPtr handle, out int x, out int y) {
2397                         POINT   pt;
2398
2399                         Win32GetCursorPos(out pt);
2400
2401                         if (handle!=IntPtr.Zero) {
2402                                 Win32ScreenToClient(handle, ref pt);
2403                         }
2404
2405                         x=pt.x;
2406                         y=pt.y;
2407                 }
2408
2409                 internal override void ScreenToClient(IntPtr handle, ref int x, ref int y)
2410                 {
2411                         POINT pnt = new POINT();                        
2412
2413                         pnt.x = x;
2414                         pnt.y = y;
2415                         Win32ScreenToClient (handle, ref pnt);
2416
2417                         x = pnt.x;
2418                         y = pnt.y;
2419                 }
2420
2421                 internal override void ClientToScreen(IntPtr handle, ref int x, ref int y) {                    
2422                         POINT   pnt = new POINT();                      
2423
2424                         pnt.x = x;
2425                         pnt.y = y;
2426
2427                         Win32ClientToScreen(handle, ref pnt);
2428
2429                         x = pnt.x;
2430                         y = pnt.y;
2431                 }
2432
2433                 internal override void ScreenToMenu(IntPtr handle, ref int x, ref int y) {
2434                         RECT    rect;
2435  
2436                         Win32GetWindowRect(handle, out rect);
2437                         x -= rect.left + SystemInformation.FrameBorderSize.Width;
2438                         y -= rect.top + SystemInformation.FrameBorderSize.Height;
2439
2440                         WindowStyles style = (WindowStyles) Win32GetWindowLong (handle, WindowLong.GWL_STYLE);
2441                         if (CreateParams.IsSet (style, WindowStyles.WS_CAPTION)) {
2442                                 y -= ThemeEngine.Current.CaptionHeight;
2443                         }
2444                 }
2445   
2446                 internal override void MenuToScreen(IntPtr handle, ref int x, ref int y) {                      
2447                         RECT    rect;
2448  
2449                         Win32GetWindowRect(handle, out rect);
2450                         x += rect.left + SystemInformation.FrameBorderSize.Width;
2451                         y += rect.top + SystemInformation.FrameBorderSize.Height + ThemeEngine.Current.CaptionHeight;
2452                         return;
2453                 }
2454
2455                 internal override void SendAsyncMethod (AsyncMethodData method)
2456                 {
2457                         Win32PostMessage(FosterParent, Msg.WM_ASYNC_MESSAGE, IntPtr.Zero, (IntPtr)GCHandle.Alloc (method));
2458                 }
2459
2460                 internal override void SetTimer (Timer timer)
2461                 {
2462                         int     index;
2463
2464                         index = timer.GetHashCode();
2465
2466                         lock (timer_list) {
2467                                 timer_list[index]=timer;
2468                         }
2469
2470                         Win32SetTimer(FosterParent, index, (uint)timer.Interval, IntPtr.Zero);
2471                 }
2472
2473                 internal override void KillTimer (Timer timer)
2474                 {
2475                         int     index;
2476
2477                         index = timer.GetHashCode();
2478
2479                         Win32KillTimer(FosterParent, index);
2480
2481                         lock (timer_list) {
2482                                 timer_list.Remove(index);
2483                         }
2484                 }
2485                 
2486                 internal override void CreateCaret(IntPtr hwnd, int width, int height) {
2487                         Win32CreateCaret(hwnd, IntPtr.Zero, width, height);
2488                         caret_visible = false;
2489                 }
2490
2491                 internal override void DestroyCaret(IntPtr hwnd) {
2492                         Win32DestroyCaret();
2493                 }
2494
2495                 internal override void SetCaretPos(IntPtr hwnd, int x, int y) {
2496                         Win32SetCaretPos(x, y);
2497                 }
2498
2499                 internal override void CaretVisible(IntPtr hwnd, bool visible) {
2500                         if (visible) {
2501                                 if (!caret_visible) {
2502                                         Win32ShowCaret(hwnd);
2503                                         caret_visible = true;
2504                                 }
2505                         } else {
2506                                 if (caret_visible) {
2507                                         Win32HideCaret(hwnd);
2508                                         caret_visible = false;
2509                                 }
2510                         }
2511                 }
2512
2513                 internal override IntPtr GetFocus() {
2514                         return Win32GetFocus();
2515                 }
2516
2517                 internal override void SetFocus(IntPtr hwnd) {
2518                         Win32SetFocus(hwnd);
2519                 }
2520
2521                 internal override IntPtr GetActive() {
2522                         return Win32GetActiveWindow();
2523                 }
2524
2525                 internal override bool GetFontMetrics(Graphics g, Font font, out int ascent, out int descent) {
2526                         IntPtr          dc;
2527                         IntPtr          prevobj;
2528                         TEXTMETRIC      tm;
2529
2530                         tm = new TEXTMETRIC();
2531
2532                         dc = Win32GetDC (IntPtr.Zero);
2533                         prevobj = Win32SelectObject (dc, font.ToHfont ());
2534                         
2535                         if (Win32GetTextMetrics (dc, ref tm) == false) {
2536                                 prevobj = Win32SelectObject (dc, prevobj);
2537                                 Win32DeleteObject (prevobj);
2538                                 Win32ReleaseDC (IntPtr.Zero, dc);
2539                                 ascent = 0;
2540                                 descent = 0;
2541                                 return false;
2542                         }
2543                         prevobj = Win32SelectObject (dc, prevobj);
2544                         Win32DeleteObject (prevobj);
2545                         Win32ReleaseDC (IntPtr.Zero, dc);
2546
2547                         ascent = tm.tmAscent;
2548                         descent = tm.tmDescent;
2549
2550                         return true;
2551                 }
2552
2553                 internal override void ScrollWindow(IntPtr hwnd, Rectangle rectangle, int XAmount, int YAmount, bool with_children) {
2554                         RECT    rect;
2555
2556                         rect = new RECT();
2557                         rect.left = rectangle.X;
2558                         rect.top = rectangle.Y;
2559                         rect.right = rectangle.Right;
2560                         rect.bottom = rectangle.Bottom;
2561
2562                         Win32ScrollWindowEx(hwnd, XAmount, YAmount, IntPtr.Zero, ref rect, IntPtr.Zero, IntPtr.Zero, ScrollWindowExFlags.SW_INVALIDATE | ScrollWindowExFlags.SW_ERASE | (with_children ? ScrollWindowExFlags.SW_SCROLLCHILDREN : ScrollWindowExFlags.SW_NONE));
2563                         Win32UpdateWindow(hwnd);
2564                 }
2565
2566                 internal override void ScrollWindow(IntPtr hwnd, int XAmount, int YAmount, bool with_children) {
2567                         Win32ScrollWindowEx(hwnd, XAmount, YAmount, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ScrollWindowExFlags.SW_INVALIDATE | ScrollWindowExFlags.SW_ERASE | (with_children ? ScrollWindowExFlags.SW_SCROLLCHILDREN : ScrollWindowExFlags.SW_NONE));
2568                 }
2569
2570                 internal override bool SystrayAdd(IntPtr hwnd, string tip, Icon icon, out ToolTip tt) {
2571                         NOTIFYICONDATA  nid;
2572
2573                         nid = new NOTIFYICONDATA();
2574
2575                         nid.cbSize = (uint)Marshal.SizeOf(nid);
2576                         nid.hWnd = hwnd;
2577                         nid.uID = 1;
2578                         nid.uCallbackMessage = (uint)Msg.WM_USER;
2579                         nid.uFlags = NotifyIconFlags.NIF_MESSAGE;
2580
2581                         if (tip != null) {       
2582                                 nid.szTip = tip;
2583                                 nid.uFlags |= NotifyIconFlags.NIF_TIP;
2584                         }
2585
2586                         if (icon != null) {
2587                                 nid.hIcon = icon.Handle;
2588                                 nid.uFlags |= NotifyIconFlags.NIF_ICON;
2589                         }
2590
2591                         tt = null;
2592
2593                         return Win32Shell_NotifyIcon(NotifyIconMessage.NIM_ADD, ref nid);
2594                 }
2595
2596                 internal override bool SystrayChange(IntPtr hwnd, string tip, Icon icon, ref ToolTip tt) {
2597                         NOTIFYICONDATA  nid;
2598
2599                         nid = new NOTIFYICONDATA();
2600
2601                         nid.cbSize = (uint)Marshal.SizeOf(nid);
2602                         nid.hIcon = icon.Handle;
2603                         nid.hWnd = hwnd;
2604                         nid.uID = 1;
2605                         nid.uCallbackMessage = (uint)Msg.WM_USER;
2606                         nid.uFlags = NotifyIconFlags.NIF_MESSAGE;
2607
2608                         if (tip != null) {
2609                                 nid.szTip = tip;
2610                                 nid.uFlags |= NotifyIconFlags.NIF_TIP;
2611                         }
2612
2613                         if (icon != null) {
2614                                 nid.hIcon = icon.Handle;
2615                                 nid.uFlags |= NotifyIconFlags.NIF_ICON;
2616                         }
2617
2618                         return Win32Shell_NotifyIcon(NotifyIconMessage.NIM_MODIFY, ref nid);
2619                 }
2620
2621                 internal override void SystrayRemove(IntPtr hwnd, ref ToolTip tt) {
2622                         NOTIFYICONDATA  nid;
2623
2624                         nid = new NOTIFYICONDATA();
2625
2626                         nid.cbSize = (uint)Marshal.SizeOf(nid);
2627                         nid.hWnd = hwnd;
2628                         nid.uID = 1;
2629                         nid.uFlags = 0;
2630
2631                         Win32Shell_NotifyIcon(NotifyIconMessage.NIM_DELETE, ref nid);
2632                 }
2633
2634 #if NET_2_0
2635                 internal override void SystrayBalloon(IntPtr hwnd, int timeout, string title, string text, ToolTipIcon icon)
2636                 {
2637                         NOTIFYICONDATA  nid;
2638
2639                         nid = new NOTIFYICONDATA();
2640
2641                         nid.cbSize = (uint)Marshal.SizeOf(nid);
2642                         nid.hWnd = hwnd;
2643                         nid.uID = 1;
2644                         nid.uFlags = NotifyIconFlags.NIF_INFO;
2645                         nid.uTimeoutOrVersion = timeout;
2646                         nid.szInfoTitle = title;
2647                         nid.szInfo = text;
2648                         nid.dwInfoFlags = icon;
2649                         
2650                         Win32Shell_NotifyIcon(NotifyIconMessage.NIM_MODIFY, ref nid);
2651                 }
2652 #endif
2653
2654                 internal override void SetBorderStyle(IntPtr handle, FormBorderStyle border_style) {
2655                         // Nothing to do on Win32
2656                 }
2657
2658                 internal override void SetMenu(IntPtr handle, Menu menu) {
2659                         // Trigger WM_NCCALC
2660                         Win32SetWindowPos(handle, IntPtr.Zero, 0, 0, 0, 0, SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE);
2661                 }
2662
2663                 internal override Point GetMenuOrigin(IntPtr handle) {
2664                         Form form = Control.FromHandle (handle) as Form;
2665                         if (form != null) {
2666                                 Hwnd.Borders borders = Hwnd.GetBorders (form.GetCreateParams (), null);
2667                                 return new Point(borders.left, borders.top);
2668                         }
2669                         return new Point(SystemInformation.FrameBorderSize.Width, SystemInformation.FrameBorderSize.Height + ThemeEngine.Current.CaptionHeight);
2670                 }
2671
2672                 internal override void SetIcon(IntPtr hwnd, Icon icon) {
2673                         Win32SendMessage(hwnd, Msg.WM_SETICON, (IntPtr)1, icon == null ? IntPtr.Zero : icon.Handle);    // 1 = large icon (0 would be small)
2674                 }
2675
2676                 internal override void ClipboardClose(IntPtr handle) {
2677                         if (handle != clip_magic) {
2678                                 throw new ArgumentException("handle is not a valid clipboard handle");
2679                         }
2680                         Win32CloseClipboard();
2681                 }
2682
2683                 internal override int ClipboardGetID(IntPtr handle, string format) {
2684                         if (handle != clip_magic) {
2685                                 throw new ArgumentException("handle is not a valid clipboard handle");
2686                         }
2687                         if (format == "Text" ) return 1;
2688                         else if (format == "Bitmap" ) return 2;
2689                         else if (format == "MetaFilePict" ) return 3;
2690                         else if (format == "SymbolicLink" ) return 4;
2691                         else if (format == "DataInterchangeFormat" ) return 5;
2692                         else if (format == "Tiff" ) return 6;
2693                         else if (format == "OEMText" ) return 7;
2694                         else if (format == "DeviceIndependentBitmap" ) return 8;
2695                         else if (format == "Palette" ) return 9;
2696                         else if (format == "PenData" ) return 10;
2697                         else if (format == "RiffAudio" ) return 11;
2698                         else if (format == "WaveAudio" ) return 12;
2699                         else if (format == "UnicodeText" ) return 13;
2700                         else if (format == "EnhancedMetafile" ) return 14;
2701                         else if (format == "FileDrop" ) return 15;
2702                         else if (format == "Locale" ) return 16;
2703
2704                         return (int)Win32RegisterClipboardFormat(format);
2705                 }
2706
2707                 internal override IntPtr ClipboardOpen(bool primary_selection) {
2708                         // Win32 does not have primary selection
2709                         Win32OpenClipboard(FosterParent);
2710                         return clip_magic;
2711                 }
2712
2713                 internal override int[] ClipboardAvailableFormats(IntPtr handle) {
2714                         uint    format;
2715                         int[]   result;
2716                         int     count;
2717
2718                         if (handle != clip_magic) {
2719                                 return null;
2720                         }
2721
2722                         // Count first
2723                         count = 0;
2724                         format = 0;
2725                         do {
2726                                 format = Win32EnumClipboardFormats(format);
2727                                 if (format != 0) {
2728                                         count++;
2729                                 }
2730                         } while (format != 0);
2731
2732                         // Now assign
2733                         result = new int[count];
2734                         count = 0;
2735                         format = 0;
2736                         do {
2737                                 format = Win32EnumClipboardFormats(format);
2738                                 if (format != 0) {
2739                                         result[count++] = (int)format;
2740                                 }
2741                         } while (format != 0);
2742
2743                         return result;
2744                 }
2745
2746
2747                 internal override object ClipboardRetrieve(IntPtr handle, int type, XplatUI.ClipboardToObject converter) {
2748                         IntPtr  hmem;
2749                         IntPtr  data;
2750                         object  obj;
2751
2752                         if (handle != clip_magic) {
2753                                 throw new ArgumentException("handle is not a valid clipboard handle");
2754                         }
2755
2756                         hmem = Win32GetClipboardData((uint)type);
2757                         if (hmem == IntPtr.Zero) {
2758                                 return null;
2759                         }
2760
2761                         data = Win32GlobalLock(hmem);
2762                         if (data == IntPtr.Zero) {
2763                                 uint error = Win32GetLastError();
2764                                 Console.WriteLine("Error: {0}", error);
2765                                 return null;
2766                         }
2767
2768                         obj = null;
2769
2770                         if (type == DataFormats.GetFormat(DataFormats.Rtf).Id) {
2771                                 obj = AnsiToString(data);
2772                         } else switch ((ClipboardFormats)type) {
2773                                 case ClipboardFormats.CF_TEXT: {
2774                                         obj = AnsiToString(data);
2775                                         break;
2776                                 }
2777
2778                                 case ClipboardFormats.CF_DIB: {
2779                                         obj = DIBtoImage(data);
2780                                         break;
2781                                 }
2782
2783                                 case ClipboardFormats.CF_UNICODETEXT: {
2784                                         obj = UnicodeToString(data);
2785                                         break;
2786                                 }
2787
2788                                 default: {
2789                                         if (converter != null && !converter(type, data, out obj)) {
2790                                                 obj = null;
2791                                         }
2792                                         break;
2793                                 }
2794                         }
2795                         Win32GlobalUnlock(hmem);
2796
2797                         return obj;
2798
2799                 }
2800
2801                 internal override void ClipboardStore(IntPtr handle, object obj, int type, XplatUI.ObjectToClipboard converter) {
2802                         byte[]  data;
2803                         IntPtr  hmem;
2804                         IntPtr  hmem_ptr;
2805
2806                         if (handle != clip_magic) {
2807                                 throw new ArgumentException("handle is not a valid clipboard handle");
2808                         }
2809
2810                         if (obj == null) {
2811                                 // Just clear it
2812                                 if (!Win32EmptyClipboard())
2813                                         throw new ExternalException("Win32EmptyClipboard");
2814                                 return;
2815                         }
2816
2817                         if (type == -1) {
2818                                 if (obj is string) {
2819                                         type = (int)ClipboardFormats.CF_UNICODETEXT;
2820                                 } else if (obj is Image) {
2821                                         type = (int)ClipboardFormats.CF_DIB;
2822                                 }
2823                         }
2824
2825                         if (type == DataFormats.GetFormat(DataFormats.Rtf).Id) {
2826                                 hmem = Marshal.StringToHGlobalAnsi((string)obj);
2827                                 if (Win32SetClipboardData((uint)type, hmem) == IntPtr.Zero )
2828                                         throw new ExternalException("Win32SetClipboardData");
2829                                 return;
2830                         } else switch((ClipboardFormats)type) {
2831                                 case ClipboardFormats.CF_UNICODETEXT: {
2832                                         hmem = Marshal.StringToHGlobalUni((string)obj);
2833                                         if (Win32SetClipboardData((uint)type, hmem) == IntPtr.Zero)
2834                                                 throw new ExternalException("Win32SetClipboardData");
2835                                         return;
2836                                 }
2837
2838                                 case ClipboardFormats.CF_TEXT: {
2839                                         hmem = Marshal.StringToHGlobalAnsi((string)obj);
2840                                         if (Win32SetClipboardData((uint)type, hmem) == IntPtr.Zero)
2841                                                 throw new ExternalException("Win32SetClipboardData");
2842                                         return;
2843                                 }
2844
2845                                 case ClipboardFormats.CF_BITMAP:
2846                                 case ClipboardFormats.CF_DIB: {
2847                                         data = ImageToDIB((Image)obj);
2848
2849                                         hmem = Win32GlobalAlloc(GAllocFlags.GMEM_MOVEABLE | GAllocFlags.GMEM_DDESHARE, data.Length);
2850                                         hmem_ptr = Win32GlobalLock(hmem);
2851                                         Marshal.Copy(data, 0, hmem_ptr, data.Length);
2852                                         Win32GlobalUnlock(hmem);
2853                                         if (Win32SetClipboardData((uint)ClipboardFormats.CF_DIB, hmem) == IntPtr.Zero)
2854                                                 throw new ExternalException("Win32SetClipboardData");
2855                                         return;
2856                                 }
2857
2858                                 default: {
2859                                         if (converter != null && converter(ref type, obj, out data)) {
2860                                                 hmem = Win32GlobalAlloc(GAllocFlags.GMEM_MOVEABLE | GAllocFlags.GMEM_DDESHARE, data.Length);
2861                                                 hmem_ptr = Win32GlobalLock(hmem);
2862                                                 Marshal.Copy(data, 0, hmem_ptr, data.Length);
2863                                                 Win32GlobalUnlock(hmem);
2864                                                 if (Win32SetClipboardData((uint)type, hmem) == IntPtr.Zero)
2865                                                         throw new ExternalException("Win32SetClipboardData");
2866                                         }
2867                                         return;
2868                                 }
2869                         }
2870                 }
2871
2872                 internal override void SetAllowDrop(IntPtr hwnd, bool allowed) {
2873                         if (allowed) {
2874                                 Win32DnD.RegisterDropTarget(hwnd);
2875                         } else {
2876                                 Win32DnD.UnregisterDropTarget(hwnd);
2877                         }
2878                 }
2879
2880                 internal override DragDropEffects StartDrag(IntPtr hwnd, object data, DragDropEffects allowedEffects) {
2881                         return Win32DnD.StartDrag(hwnd, data, allowedEffects);
2882                 }
2883
2884                 // XXX this doesn't work at all for FrameStyle.Dashed - it draws like Thick, and in the Thick case
2885                 // the corners are drawn incorrectly.
2886                 internal override void DrawReversibleFrame (Rectangle rectangle, Color backColor, FrameStyle style) {
2887                         IntPtr          hdc;
2888                         IntPtr          pen;
2889                         IntPtr          oldpen;
2890                         COLORREF        clrRef = new COLORREF();
2891
2892                         // If we want the standard hatch pattern we would
2893                         // need to create a brush
2894
2895                         clrRef.R = backColor.R;
2896                         clrRef.G = backColor.G;
2897                         clrRef.B = backColor.B;
2898
2899                         // Grab a pen
2900                         pen = Win32CreatePen (style == FrameStyle.Thick ? PenStyle.PS_SOLID : PenStyle.PS_DASH,
2901                                               style == FrameStyle.Thick ? 4 : 2, ref clrRef);
2902
2903                         hdc = Win32GetDC(IntPtr.Zero);
2904                         Win32SetROP2(hdc, ROP2DrawMode.R2_NOT);
2905                         oldpen = Win32SelectObject(hdc, pen);
2906
2907                         Win32MoveToEx(hdc, rectangle.Left, rectangle.Top, IntPtr.Zero);
2908                         if ((rectangle.Width > 0) && (rectangle.Height > 0)) {
2909                                 Win32LineTo(hdc, rectangle.Right, rectangle.Top);
2910                                 Win32LineTo(hdc, rectangle.Right, rectangle.Bottom);
2911                                 Win32LineTo(hdc, rectangle.Left, rectangle.Bottom);
2912                                 Win32LineTo(hdc, rectangle.Left, rectangle.Top);
2913                         } else {
2914                                 if (rectangle.Width > 0) {
2915                                         Win32LineTo(hdc, rectangle.Right, rectangle.Top);
2916                                 } else {
2917                                         Win32LineTo(hdc, rectangle.Left, rectangle.Bottom);
2918                                 }
2919                         }
2920
2921                         Win32SelectObject(hdc, oldpen);
2922                         Win32DeleteObject(pen);
2923
2924                         Win32ReleaseDC(IntPtr.Zero, hdc);
2925                 }
2926
2927                 internal override void DrawReversibleLine(Point start, Point end, Color backColor) {
2928                         IntPtr          hdc;
2929                         IntPtr          pen;
2930                         IntPtr          oldpen;
2931                         POINT           pt;
2932                         COLORREF        clrRef = new COLORREF();
2933
2934                         pt = new POINT();
2935                         pt.x = 0;
2936                         pt.y = 0;
2937                         Win32ClientToScreen(IntPtr.Zero, ref pt);
2938
2939                         // If we want the standard hatch pattern we would
2940                         // need to create a brush
2941
2942                         clrRef.R = backColor.R;
2943                         clrRef.G = backColor.G;
2944                         clrRef.B = backColor.B;
2945
2946                         // Grab a pen
2947                         pen = Win32CreatePen(PenStyle.PS_SOLID, 1, ref clrRef);
2948
2949                         hdc = Win32GetDC(IntPtr.Zero);
2950                         Win32SetROP2(hdc, ROP2DrawMode.R2_NOT);
2951                         oldpen = Win32SelectObject(hdc, pen);
2952
2953                         Win32MoveToEx(hdc, pt.x + start.X, pt.y + start.Y, IntPtr.Zero);
2954                         Win32LineTo(hdc, pt.x + end.X, pt.y + end.Y);
2955
2956                         Win32SelectObject(hdc, oldpen);
2957                         Win32DeleteObject(pen);
2958
2959                         Win32ReleaseDC(IntPtr.Zero, hdc);
2960                 }
2961
2962                 internal override void FillReversibleRectangle (Rectangle rectangle, Color backColor)
2963                 {
2964                         RECT    rect;
2965
2966                         rect = new RECT();
2967                         rect.left = rectangle.Left;
2968                         rect.top = rectangle.Top;
2969                         rect.right = rectangle.Right;
2970                         rect.bottom = rectangle.Bottom;
2971
2972                         IntPtr          hdc;
2973                         IntPtr          brush;
2974                         IntPtr          oldbrush;
2975                         COLORREF        clrRef = new COLORREF();
2976
2977                         clrRef.R = backColor.R;
2978                         clrRef.G = backColor.G;
2979                         clrRef.B = backColor.B;
2980
2981                         // Grab a brush
2982                         brush = Win32CreateSolidBrush (clrRef);
2983
2984                         hdc = Win32GetDC(IntPtr.Zero);
2985                         oldbrush = Win32SelectObject(hdc, brush);
2986
2987                         Win32PatBlt (hdc, rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height, PatBltRop.DSTINVERT);
2988
2989                         Win32SelectObject(hdc, oldbrush);
2990                         Win32DeleteObject(brush);
2991
2992                         Win32ReleaseDC(IntPtr.Zero, hdc);
2993                 }
2994
2995                 internal override void DrawReversibleRectangle(IntPtr handle, Rectangle rect, int line_width) {
2996                         IntPtr          hdc;
2997                         IntPtr          pen;
2998                         IntPtr          oldpen;
2999                         POINT           pt;
3000
3001                         pt = new POINT();
3002                         pt.x = 0;
3003                         pt.y = 0;
3004                         Win32ClientToScreen(handle, ref pt);
3005
3006                         // If we want the standard hatch pattern we would
3007                         // need to create a brush
3008
3009                         // Grab a pen
3010                         pen = Win32CreatePen(PenStyle.PS_SOLID, line_width, IntPtr.Zero);
3011
3012                         hdc = Win32GetDC(IntPtr.Zero);
3013                         Win32SetROP2(hdc, ROP2DrawMode.R2_NOT);
3014                         oldpen = Win32SelectObject(hdc, pen);
3015
3016                         Control c = Control.FromHandle (handle);
3017                         if (c != null) {
3018                                 RECT window_rect;
3019                                 Win32GetWindowRect (c.Handle, out window_rect);
3020                                 Region r = new Region (new Rectangle(window_rect.left, window_rect.top, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top));
3021                                 Win32ExtSelectClipRgn(hdc, r.GetHrgn (Graphics.FromHdc (hdc)), (int) ClipCombineMode.RGN_AND);
3022                         }
3023
3024                         Win32MoveToEx(hdc, pt.x + rect.Left, pt.y + rect.Top, IntPtr.Zero);
3025                         if ((rect.Width > 0) && (rect.Height > 0)) {
3026                                 Win32LineTo(hdc, pt.x + rect.Right, pt.y + rect.Top);
3027                                 Win32LineTo(hdc, pt.x + rect.Right, pt.y + rect.Bottom);
3028                                 Win32LineTo(hdc, pt.x + rect.Left, pt.y + rect.Bottom);
3029                                 Win32LineTo(hdc, pt.x + rect.Left, pt.y + rect.Top);
3030                         } else {
3031                                 if (rect.Width > 0) {
3032                                         Win32LineTo(hdc, pt.x + rect.Right, pt.y + rect.Top);
3033                                 } else {
3034                                         Win32LineTo(hdc, pt.x + rect.Left, pt.y + rect.Bottom);
3035                                 }
3036                         }
3037
3038                         Win32SelectObject(hdc, oldpen);
3039                         Win32DeleteObject(pen);
3040                         if (c != null)
3041                                 Win32ExtSelectClipRgn(hdc, IntPtr.Zero, (int) ClipCombineMode.RGN_COPY);
3042
3043                         Win32ReleaseDC(IntPtr.Zero, hdc);
3044                 }
3045
3046                 internal override SizeF GetAutoScaleSize(Font font) {
3047                         Graphics        g;
3048                         float           width;
3049                         string          magic_string = "The quick brown fox jumped over the lazy dog.";
3050                         double          magic_number = 44.549996948242189;
3051
3052                         g = Graphics.FromHwnd(FosterParent);
3053
3054                         width = (float) (g.MeasureString (magic_string, font).Width / magic_number);
3055                         return new SizeF(width, font.Height);
3056                 }
3057
3058                 internal override IntPtr SendMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
3059                         return Win32SendMessage(hwnd, message, wParam, lParam);
3060                 }
3061
3062                 internal override bool PostMessage (IntPtr hwnd, Msg message, IntPtr wParam, IntPtr lParam) {
3063                         return Win32PostMessage(hwnd, message, wParam, lParam);
3064                 }
3065
3066                 internal override int SendInput (IntPtr hwnd, Queue keys) {
3067                         INPUT[] inputs = new INPUT[keys.Count];
3068                         const Int32 INPUT_KEYBOARD = 1;
3069                         uint returns = 0;
3070                         int i = 0;
3071                         while (keys.Count > 0) {
3072                                 MSG msg = (MSG)keys.Dequeue();
3073
3074                                 
3075                                 inputs[i].ki.wScan = 0;
3076                                 inputs[i].ki.time = 0;
3077                                 inputs[i].ki.dwFlags = (Int32)(msg.message == Msg.WM_KEYUP ? InputFlags.KEYEVENTF_KEYUP : 0);
3078                                 inputs[i].ki.wVk = (short)msg.wParam.ToInt32();
3079                                 inputs[i].type = INPUT_KEYBOARD;
3080                                 i++;
3081                         }
3082                         returns = Win32SendInput((UInt32)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
3083
3084                         return (int) returns;
3085                 }
3086
3087                 internal override int KeyboardSpeed {
3088                         get {
3089                                 int speed = 0;
3090                                 Win32SystemParametersInfo(SPIAction.SPI_GETKEYBOARDSPEED, 0, ref speed, 0);
3091                                 //
3092                                 // Return values range from 0 to 31 which map to 2.5 to 30 repetitions per second.
3093                                 //
3094                                 return speed;
3095                         }
3096                 }
3097
3098                 internal override int KeyboardDelay {
3099                         get {
3100                                 int delay = 1;
3101                                 Win32SystemParametersInfo(SPIAction.SPI_GETKEYBOARDDELAY, 0, ref delay, 0);
3102                                 //
3103                                 // Return values must range from 0 to 4, 0 meaning 250ms,
3104                                 // and 4 meaning 1000 ms.
3105                                 //
3106                                 return delay;
3107                         }
3108                 }
3109
3110                 private class WinBuffer
3111                 {
3112                         public IntPtr hdc;
3113                         public IntPtr bitmap;
3114
3115                         public WinBuffer (IntPtr hdc, IntPtr bitmap)
3116                         {
3117                                 this.hdc = hdc;
3118                                 this.bitmap = bitmap;
3119                         }
3120                 }
3121
3122                 internal override void CreateOffscreenDrawable (IntPtr handle, int width, int height, out object offscreen_drawable)
3123                 {
3124                         Graphics destG = Graphics.FromHwnd (handle);
3125                         IntPtr destHdc = destG.GetHdc ();
3126
3127                         IntPtr srcHdc = Win32CreateCompatibleDC (destHdc);
3128                         IntPtr srcBmp = Win32CreateCompatibleBitmap (destHdc, width, height);
3129                         Win32SelectObject (srcHdc, srcBmp);
3130
3131                         offscreen_drawable = new WinBuffer (srcHdc, srcBmp);
3132
3133                         destG.ReleaseHdc (destHdc);
3134                 }
3135
3136                 internal override Graphics GetOffscreenGraphics (object offscreen_drawable)
3137                 {
3138                         return Graphics.FromHdc (((WinBuffer)offscreen_drawable).hdc);
3139                 }
3140
3141                 internal override void BlitFromOffscreen (IntPtr dest_handle, Graphics dest_dc, object offscreen_drawable, Graphics offscreen_dc, Rectangle r)
3142                 {
3143                         WinBuffer wb = (WinBuffer)offscreen_drawable;
3144
3145                         IntPtr destHdc = dest_dc.GetHdc ();
3146                         Win32BitBlt (destHdc, r.Left, r.Top, r.Width, r.Height, wb.hdc, r.Left, r.Top, TernaryRasterOperations.SRCCOPY);
3147                         dest_dc.ReleaseHdc (destHdc);
3148                 }
3149
3150                 internal override void DestroyOffscreenDrawable (object offscreen_drawable)
3151                 {
3152                         WinBuffer wb = (WinBuffer)offscreen_drawable;
3153
3154                         Win32DeleteObject (wb.bitmap);
3155                         Win32DeleteDC (wb.hdc);
3156                 }
3157
3158                 internal override event EventHandler Idle;
3159                 #endregion      // Public Static Methods
3160
3161                 #region Win32 Imports
3162                 [DllImport ("kernel32.dll", EntryPoint="GetLastError", CallingConvention=CallingConvention.StdCall)]
3163                 private extern static uint Win32GetLastError();
3164
3165                 [DllImport ("user32.dll", EntryPoint="CreateWindowExW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3166                 internal extern static IntPtr Win32CreateWindow(WindowExStyles dwExStyle, string lpClassName, string lpWindowName, WindowStyles dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lParam);
3167
3168                 [DllImport ("user32.dll", EntryPoint="DestroyWindow", CallingConvention=CallingConvention.StdCall)]
3169                 internal extern static bool Win32DestroyWindow(IntPtr hWnd);
3170
3171                 [DllImport ("user32.dll", EntryPoint="PeekMessageW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3172                 internal extern static bool Win32PeekMessage(ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax, uint flags);
3173
3174                 [DllImport ("user32.dll", EntryPoint="GetMessageW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3175                 internal extern static bool Win32GetMessage(ref MSG msg, IntPtr hWnd, int wFilterMin, int wFilterMax);
3176
3177                 [DllImport ("user32.dll", EntryPoint="TranslateMessage", CallingConvention=CallingConvention.StdCall)]
3178                 internal extern static bool Win32TranslateMessage(ref MSG msg);
3179
3180                 [DllImport ("user32.dll", EntryPoint="DispatchMessageW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3181                 internal extern static IntPtr Win32DispatchMessage(ref MSG msg);
3182
3183                 [DllImport ("user32.dll", EntryPoint="MoveWindow", CallingConvention=CallingConvention.StdCall)]
3184                 internal extern static bool Win32MoveWindow(IntPtr hWnd, int x, int y, int width, int height, bool repaint);
3185
3186                 [DllImport ("user32.dll", EntryPoint="SetWindowPos", CallingConvention=CallingConvention.StdCall)]
3187                 internal extern static bool Win32SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags Flags);
3188
3189                 [DllImport ("user32.dll", EntryPoint="SetWindowPos", CallingConvention=CallingConvention.StdCall)]
3190                 internal extern static bool Win32SetWindowPos(IntPtr hWnd, SetWindowPosZOrder pos, int x, int y, int cx, int cy, SetWindowPosFlags Flags);
3191
3192                 [DllImport ("user32.dll", EntryPoint="SetWindowTextW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3193                 internal extern static bool Win32SetWindowText(IntPtr hWnd, string lpString);
3194
3195                 [DllImport ("user32.dll", EntryPoint="GetWindowTextW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3196                 internal extern static bool Win32GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
3197
3198                 [DllImport ("user32.dll", EntryPoint="SetParent", CallingConvention=CallingConvention.StdCall)]
3199                 internal extern static IntPtr Win32SetParent(IntPtr hWnd, IntPtr hParent);
3200
3201                 [DllImport ("user32.dll", EntryPoint="RegisterClassW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3202                 private extern static bool Win32RegisterClass(ref WNDCLASS wndClass);
3203
3204                 [DllImport ("user32.dll", EntryPoint="LoadCursorW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3205                 private extern static IntPtr Win32LoadCursor(IntPtr hInstance, LoadCursorType type);
3206
3207                 [DllImport ("user32.dll", EntryPoint="ShowCursor", CallingConvention=CallingConvention.StdCall)]
3208                 private extern static IntPtr Win32ShowCursor(bool bShow);
3209
3210                 [DllImport ("user32.dll", EntryPoint="SetCursor", CallingConvention=CallingConvention.StdCall)]
3211                 private extern static IntPtr Win32SetCursor(IntPtr hCursor);
3212
3213                 [DllImport ("user32.dll", EntryPoint="CreateCursor", CallingConvention=CallingConvention.StdCall)]
3214                 private extern static IntPtr Win32CreateCursor(IntPtr hInstance, int xHotSpot, int yHotSpot, int nWidth, int nHeight, Byte[] pvANDPlane, Byte[] pvORPlane);
3215
3216                 [DllImport ("user32.dll", EntryPoint="DestroyCursor", CallingConvention=CallingConvention.StdCall)]
3217                 private extern static bool Win32DestroyCursor(IntPtr hCursor);
3218
3219                 [DllImport ("user32.dll", EntryPoint = "DrawIcon", CallingConvention = CallingConvention.StdCall)]
3220                 private extern static bool Win32DrawIcon (IntPtr hDC, int X, int Y, IntPtr hIcon);
3221                 
3222                 [DllImport ("user32.dll", EntryPoint="DefWindowProcW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3223                 private extern static IntPtr Win32DefWindowProc(IntPtr hWnd, Msg Msg, IntPtr wParam, IntPtr lParam);
3224
3225                 //[DllImport ("user32.dll", EntryPoint="DefDlgProcW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3226                 //private extern static IntPtr Win32DefDlgProc(IntPtr hWnd, Msg Msg, IntPtr wParam, IntPtr lParam);
3227
3228                 [DllImport ("user32.dll", EntryPoint="PostQuitMessage", CallingConvention=CallingConvention.StdCall)]
3229                 private extern static IntPtr Win32PostQuitMessage(int nExitCode);
3230
3231                 [DllImport ("user32.dll", EntryPoint="UpdateWindow", CallingConvention=CallingConvention.StdCall)]
3232                 private extern static IntPtr Win32UpdateWindow(IntPtr hWnd);
3233
3234                 [DllImport ("user32.dll", EntryPoint="GetUpdateRect", CallingConvention=CallingConvention.StdCall)]
3235                 private extern static bool Win32GetUpdateRect(IntPtr hWnd, ref RECT rect, bool erase);
3236
3237                 [DllImport ("user32.dll", EntryPoint="BeginPaint", CallingConvention=CallingConvention.StdCall)]
3238                 private extern static IntPtr Win32BeginPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
3239
3240                 [DllImport ("user32.dll", EntryPoint="EndPaint", CallingConvention=CallingConvention.StdCall)]
3241                 private extern static bool Win32EndPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
3242
3243                 [DllImport ("user32.dll", EntryPoint="GetDC", CallingConvention=CallingConvention.StdCall)]
3244                 private extern static IntPtr Win32GetDC(IntPtr hWnd);
3245
3246                 [DllImport ("user32.dll", EntryPoint="GetWindowDC", CallingConvention=CallingConvention.StdCall)]
3247                 private extern static IntPtr Win32GetWindowDC(IntPtr hWnd);
3248
3249                 //[DllImport ("user32.dll", EntryPoint="GetDCEx", CallingConvention=CallingConvention.StdCall)]
3250                 //private extern static IntPtr Win32GetDCEx(IntPtr hWnd, IntPtr hRgn, DCExFlags flags);
3251
3252                 [DllImport ("user32.dll", EntryPoint="ReleaseDC", CallingConvention=CallingConvention.StdCall)]
3253                 private extern static IntPtr Win32ReleaseDC(IntPtr hWnd, IntPtr hDC);
3254
3255                 [DllImport ("user32.dll", EntryPoint="MessageBoxW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3256                 private extern static IntPtr Win32MessageBox(IntPtr hParent, string pText, string pCaption, uint uType);
3257
3258                 [DllImport ("user32.dll", EntryPoint="InvalidateRect", CallingConvention=CallingConvention.StdCall)]
3259                 private extern static IntPtr Win32InvalidateRect(IntPtr hWnd, ref RECT lpRect, bool bErase);
3260
3261                 //[DllImport ("user32.dll", EntryPoint="InvalidateRect", CallingConvention=CallingConvention.StdCall)]
3262                 //private extern static IntPtr Win32InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase);
3263
3264                 [DllImport ("user32.dll", EntryPoint="SetCapture", CallingConvention=CallingConvention.StdCall)]
3265                 private extern static IntPtr Win32SetCapture(IntPtr hWnd);
3266
3267                 [DllImport ("user32.dll", EntryPoint="ReleaseCapture", CallingConvention=CallingConvention.StdCall)]
3268                 private extern static IntPtr Win32ReleaseCapture();
3269
3270                 [DllImport ("user32.dll", EntryPoint="GetWindowRect", CallingConvention=CallingConvention.StdCall)]
3271                 private extern static IntPtr Win32GetWindowRect(IntPtr hWnd, out RECT rect);
3272
3273                 [DllImport ("user32.dll", EntryPoint="GetClientRect", CallingConvention=CallingConvention.StdCall)]
3274                 private extern static IntPtr Win32GetClientRect(IntPtr hWnd, out RECT rect);
3275
3276                 [DllImport ("user32.dll", EntryPoint="ScreenToClient", CallingConvention=CallingConvention.StdCall)]
3277                 private extern static bool Win32ScreenToClient(IntPtr hWnd, ref POINT pt);
3278
3279                 [DllImport ("user32.dll", EntryPoint="ClientToScreen", CallingConvention=CallingConvention.StdCall)]
3280                 private extern static bool Win32ClientToScreen(IntPtr hWnd, ref POINT pt);
3281
3282                 // This function returns the parent OR THE OWNER!
3283                 // Use GetAncestor to only get the parent.
3284                 [DllImport ("user32.dll", EntryPoint="GetParent", CallingConvention=CallingConvention.StdCall)]
3285                 private extern static IntPtr Win32GetParent(IntPtr hWnd);
3286
3287                 [DllImport ("user32.dll", EntryPoint = "GetAncestor", CallingConvention = CallingConvention.StdCall)]
3288                 private extern static IntPtr Win32GetAncestor (IntPtr hWnd, AncestorType flags);
3289
3290                 [DllImport ("user32.dll", EntryPoint="SetActiveWindow", CallingConvention=CallingConvention.StdCall)]
3291                 private extern static IntPtr Win32SetActiveWindow(IntPtr hWnd);
3292
3293                 [DllImport ("user32.dll", EntryPoint="AdjustWindowRectEx", CallingConvention=CallingConvention.StdCall)]
3294                 private extern static bool Win32AdjustWindowRectEx(ref RECT lpRect, int dwStyle, bool bMenu, int dwExStyle);
3295
3296                 [DllImport ("user32.dll", EntryPoint="GetCursorPos", CallingConvention=CallingConvention.StdCall)]
3297                 private extern static bool Win32GetCursorPos(out POINT lpPoint);
3298
3299                 [DllImport ("user32.dll", EntryPoint="SetCursorPos", CallingConvention=CallingConvention.StdCall)]
3300                 private extern static bool Win32SetCursorPos(int x, int y);
3301
3302                 //[DllImport ("user32.dll", EntryPoint="GetWindowPlacement", CallingConvention=CallingConvention.StdCall)]
3303                 //private extern static bool Win32GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
3304
3305                 [DllImport ("user32.dll", EntryPoint="TrackMouseEvent", CallingConvention=CallingConvention.StdCall)]
3306                 private extern static bool Win32TrackMouseEvent(ref TRACKMOUSEEVENT tme);
3307
3308                 //[DllImport ("gdi32.dll", EntryPoint="CreateBrushIndirect", CallingConvention=CallingConvention.StdCall)]
3309                 //private extern static IntPtr Win32CreateBrushIndirect(ref LOGBRUSH lb);
3310
3311                 [DllImport ("gdi32.dll", EntryPoint="CreateSolidBrush", CallingConvention=CallingConvention.StdCall)]
3312                 private extern static IntPtr Win32CreateSolidBrush(COLORREF clrRef);
3313
3314                 [DllImport ("gdi32.dll", EntryPoint="PatBlt", CallingConvention=CallingConvention.StdCall)]
3315                 private extern static int Win32PatBlt(IntPtr hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, PatBltRop dwRop);
3316
3317                 [DllImport ("user32.dll", EntryPoint="SetWindowLong", CallingConvention=CallingConvention.StdCall)]
3318                 private extern static uint Win32SetWindowLong(IntPtr hwnd, WindowLong index, uint value);
3319
3320                 [DllImport ("user32.dll", EntryPoint="GetWindowLong", CallingConvention=CallingConvention.StdCall)]
3321                 private extern static uint Win32GetWindowLong(IntPtr hwnd, WindowLong index);
3322
3323                 [DllImport ("user32.dll", EntryPoint="SetLayeredWindowAttributes", CallingConvention=CallingConvention.StdCall)]
3324                 private extern static uint Win32SetLayeredWindowAttributes (IntPtr hwnd, COLORREF crKey, byte bAlpha, LayeredWindowAttributes dwFlags);
3325
3326                 [DllImport ("user32.dll", EntryPoint="GetLayeredWindowAttributes", CallingConvention=CallingConvention.StdCall)]
3327                 private extern static uint Win32GetLayeredWindowAttributes (IntPtr hwnd, out COLORREF pcrKey, out byte pbAlpha, out LayeredWindowAttributes pwdFlags);
3328
3329                 [DllImport ("gdi32.dll", EntryPoint="DeleteObject", CallingConvention=CallingConvention.StdCall)]
3330                 private extern static bool Win32DeleteObject(IntPtr o);
3331
3332                 [DllImport ("user32.dll", EntryPoint="GetKeyState", CallingConvention=CallingConvention.StdCall)]
3333                 private extern static short Win32GetKeyState(VirtualKeys nVirtKey);
3334
3335                 [DllImport ("user32.dll", EntryPoint="GetDesktopWindow", CallingConvention=CallingConvention.StdCall)]
3336                 private extern static IntPtr Win32GetDesktopWindow();
3337
3338                 [DllImport ("user32.dll", EntryPoint="SetTimer", CallingConvention=CallingConvention.StdCall)]
3339                 private extern static IntPtr Win32SetTimer(IntPtr hwnd, int nIDEvent, uint uElapse, IntPtr timerProc);
3340
3341                 [DllImport ("user32.dll", EntryPoint="KillTimer", CallingConvention=CallingConvention.StdCall)]
3342                 private extern static IntPtr Win32KillTimer(IntPtr hwnd, int nIDEvent);
3343
3344                 [DllImport ("user32.dll", EntryPoint="ShowWindow", CallingConvention=CallingConvention.StdCall)]
3345                 private extern static IntPtr Win32ShowWindow(IntPtr hwnd, WindowPlacementFlags nCmdShow);
3346
3347                 [DllImport ("user32.dll", EntryPoint="EnableWindow", CallingConvention=CallingConvention.StdCall)]
3348                 private extern static IntPtr Win32EnableWindow(IntPtr hwnd, bool Enabled);
3349
3350                 [DllImport ("user32.dll", EntryPoint="SetFocus", CallingConvention=CallingConvention.StdCall)]
3351                 internal extern static IntPtr Win32SetFocus(IntPtr hwnd);
3352
3353                 [DllImport ("user32.dll", EntryPoint="GetFocus", CallingConvention=CallingConvention.StdCall)]
3354                 internal extern static IntPtr Win32GetFocus();
3355
3356                 [DllImport ("user32.dll", EntryPoint="CreateCaret", CallingConvention=CallingConvention.StdCall)]
3357                 internal extern static bool Win32CreateCaret(IntPtr hwnd, IntPtr hBitmap, int nWidth, int nHeight);
3358
3359                 [DllImport ("user32.dll", EntryPoint="DestroyCaret", CallingConvention=CallingConvention.StdCall)]
3360                 private  extern static bool Win32DestroyCaret();
3361
3362                 [DllImport ("user32.dll", EntryPoint="ShowCaret", CallingConvention=CallingConvention.StdCall)]
3363                 private  extern static bool Win32ShowCaret(IntPtr hwnd);
3364
3365                 [DllImport ("user32.dll", EntryPoint="HideCaret", CallingConvention=CallingConvention.StdCall)]
3366                 private  extern static bool Win32HideCaret(IntPtr hwnd);
3367
3368                 [DllImport ("user32.dll", EntryPoint="SetCaretPos", CallingConvention=CallingConvention.StdCall)]
3369                 private  extern static bool Win32SetCaretPos(int X, int Y);
3370
3371                 //[DllImport ("user32.dll", EntryPoint="GetCaretBlinkTime", CallingConvention=CallingConvention.StdCall)]
3372                 //private  extern static uint Win32GetCaretBlinkTime();
3373
3374                 [DllImport ("gdi32.dll", EntryPoint="GetTextMetricsW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3375                 internal extern static bool Win32GetTextMetrics(IntPtr hdc, ref TEXTMETRIC tm);
3376
3377                 [DllImport ("gdi32.dll", EntryPoint="SelectObject", CallingConvention=CallingConvention.StdCall)]
3378                 internal extern static IntPtr Win32SelectObject(IntPtr hdc, IntPtr hgdiobject);
3379
3380                 //[DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3381                 //private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, ref RECT prcScroll, ref RECT prcClip, IntPtr hrgnUpdate, out RECT prcUpdate, ScrollWindowExFlags flags);
3382
3383                 //[DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3384                 //private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, IntPtr prcScroll, ref RECT prcClip, IntPtr hrgnUpdate, out RECT prcUpdate, ScrollWindowExFlags flags);
3385
3386                 //[DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3387                 //private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, ref RECT prcScroll, IntPtr prcClip, IntPtr hrgnUpdate, out RECT prcUpdate, ScrollWindowExFlags flags);
3388
3389                 [DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3390                 private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, IntPtr prcScroll, ref RECT prcClip, IntPtr hrgnUpdate, IntPtr prcUpdate, ScrollWindowExFlags flags);
3391
3392                 //[DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3393                 //private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, ref RECT prcScroll, IntPtr prcClip, IntPtr hrgnUpdate, IntPtr prcUpdate, ScrollWindowExFlags flags);
3394
3395                 //[DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3396                 //private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, ref RECT prcScroll, ref RECT prcClip, IntPtr hrgnUpdate, IntPtr prcUpdate, ScrollWindowExFlags flags);
3397
3398                 [DllImport ("user32.dll", EntryPoint="ScrollWindowEx", CallingConvention=CallingConvention.StdCall)]
3399                 private extern static bool Win32ScrollWindowEx(IntPtr hwnd, int dx, int dy, IntPtr prcScroll, IntPtr prcClip, IntPtr hrgnUpdate, IntPtr prcUpdate, ScrollWindowExFlags flags);
3400
3401                 [DllImport ("user32.dll", EntryPoint="GetActiveWindow", CallingConvention=CallingConvention.StdCall)]
3402                 private extern static IntPtr Win32GetActiveWindow();
3403
3404                 [DllImport ("user32.dll", EntryPoint="GetSystemMetrics", CallingConvention=CallingConvention.StdCall)]
3405                 private extern static int Win32GetSystemMetrics(SystemMetrics nIndex);
3406
3407                 [DllImport ("shell32.dll", EntryPoint="Shell_NotifyIconW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3408                 private extern static bool Win32Shell_NotifyIcon(NotifyIconMessage dwMessage, ref NOTIFYICONDATA lpData);
3409
3410                 [DllImport ("gdi32.dll", EntryPoint="CreateRectRgn", CallingConvention=CallingConvention.StdCall)]
3411                 internal extern static IntPtr Win32CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);
3412
3413                 [DllImport ("user32.dll", EntryPoint="IsWindowEnabled", CallingConvention=CallingConvention.StdCall)]
3414                 private extern static bool IsWindowEnabled(IntPtr hwnd);
3415
3416                 [DllImport ("user32.dll", EntryPoint="IsWindowVisible", CallingConvention=CallingConvention.StdCall)]
3417                 private extern static bool IsWindowVisible(IntPtr hwnd);
3418
3419                 //[DllImport ("user32.dll", EntryPoint="SetClassLong", CallingConvention=CallingConvention.StdCall)]
3420                 //private extern static bool Win32SetClassLong(IntPtr hwnd, ClassLong nIndex, IntPtr dwNewLong);
3421
3422                 [DllImport ("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3423                 private extern static IntPtr Win32SendMessage(IntPtr hwnd, Msg msg, IntPtr wParam, IntPtr lParam);
3424
3425                 [DllImport ("user32.dll", EntryPoint="PostMessageW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3426                 private extern static bool Win32PostMessage(IntPtr hwnd, Msg msg, IntPtr wParam, IntPtr lParam);
3427
3428                 [DllImport ("user32.dll", EntryPoint="SendInput", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3429                 private extern static UInt32 Win32SendInput(UInt32 nInputs, [MarshalAs(UnmanagedType.LPArray)] INPUT[] inputs, Int32 cbSize);
3430
3431                 [DllImport ("user32.dll", EntryPoint="SystemParametersInfoW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3432                 private extern static bool Win32SystemParametersInfo(SPIAction uiAction, uint uiParam, ref RECT rect, uint fWinIni);
3433                 
3434                 //[DllImport ("user32.dll", EntryPoint="SystemParametersInfoW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3435                 //private extern static bool Win32SystemParametersInfo(SPIAction uiAction, uint uiParam, ref uint value, uint fWinIni);
3436
3437                 [DllImport ("user32.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
3438                 private extern static bool Win32SystemParametersInfo (SPIAction uiAction, uint uiParam, ref int value, uint fWinIni);
3439
3440                 [DllImport ("user32.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
3441                 private extern static bool Win32SystemParametersInfo (SPIAction uiAction, uint uiParam, ref bool value, uint fWinIni);
3442
3443                 [DllImport ("user32.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
3444                 private extern static bool Win32SystemParametersInfo (SPIAction uiAction, uint uiParam, ref ANIMATIONINFO value, uint fWinIni);
3445
3446                 [DllImport ("user32.dll", EntryPoint="OpenClipboard", CallingConvention=CallingConvention.StdCall)]
3447                 private extern static bool Win32OpenClipboard(IntPtr hwnd);
3448
3449                 [DllImport ("user32.dll", EntryPoint="EmptyClipboard", CallingConvention=CallingConvention.StdCall)]
3450                 private extern static bool Win32EmptyClipboard();
3451
3452                 [DllImport ("user32.dll", EntryPoint="RegisterClipboardFormatW", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall)]
3453                 private extern static uint Win32RegisterClipboardFormat(string format);
3454
3455                 [DllImport ("user32.dll", EntryPoint="CloseClipboard", CallingConvention=CallingConvention.StdCall)]
3456                 private extern static bool Win32CloseClipboard();
3457
3458                 [DllImport ("user32.dll", EntryPoint="EnumClipboardFormats", CallingConvention=CallingConvention.StdCall)]
3459                 private extern static uint Win32EnumClipboardFormats(uint format);
3460
3461                 [DllImport ("user32.dll", EntryPoint="GetClipboardData", CallingConvention=CallingConvention.StdCall)]
3462                 private extern static IntPtr Win32GetClipboardData(uint format);
3463
3464                 [DllImport ("user32.dll", EntryPoint="SetClipboardData", CallingConvention=CallingConvention.StdCall)]
3465                 private extern static IntPtr Win32SetClipboardData(uint format, IntPtr handle);
3466
3467                 [DllImport ("kernel32.dll", EntryPoint="GlobalAlloc", CallingConvention=CallingConvention.StdCall)]
3468                 internal extern static IntPtr Win32GlobalAlloc(GAllocFlags Flags, int dwBytes);
3469
3470                 [DllImport ("kernel32.dll", EntryPoint="CopyMemory", CallingConvention=CallingConvention.StdCall)]
3471                 internal extern static void Win32CopyMemory(IntPtr Destination, IntPtr Source, int length);
3472
3473                 [DllImport ("kernel32.dll", EntryPoint="GlobalFree", CallingConvention=CallingConvention.StdCall)]
3474                 internal extern static IntPtr Win32GlobalFree(IntPtr hMem);
3475
3476                 [DllImport ("kernel32.dll", EntryPoint="GlobalSize", CallingConvention=CallingConvention.StdCall)]
3477                 internal extern static uint Win32GlobalSize(IntPtr hMem);
3478
3479                 [DllImport ("kernel32.dll", EntryPoint="GlobalLock", CallingConvention=CallingConvention.StdCall)]
3480                 internal extern static IntPtr Win32GlobalLock(IntPtr hMem);
3481
3482                 [DllImport ("kernel32.dll", EntryPoint="GlobalUnlock", CallingConvention=CallingConvention.StdCall)]
3483                 internal extern static IntPtr Win32GlobalUnlock(IntPtr hMem);
3484
3485                 [DllImport ("gdi32.dll", EntryPoint="SetROP2", CallingConvention=CallingConvention.StdCall)]
3486                 internal extern static int Win32SetROP2(IntPtr hdc, ROP2DrawMode fnDrawMode);
3487
3488                 [DllImport ("gdi32.dll", EntryPoint="MoveToEx", CallingConvention=CallingConvention.StdCall)]
3489                 internal extern static bool Win32MoveToEx(IntPtr hdc, int x, int y, ref POINT lpPoint);
3490
3491                 [DllImport ("gdi32.dll", EntryPoint="MoveToEx", CallingConvention=CallingConvention.StdCall)]
3492                 internal extern static bool Win32MoveToEx(IntPtr hdc, int x, int y, IntPtr lpPoint);
3493
3494                 [DllImport ("gdi32.dll", EntryPoint="LineTo", CallingConvention=CallingConvention.StdCall)]
3495                 internal extern static bool Win32LineTo(IntPtr hdc, int x, int y);
3496
3497                 [DllImport ("gdi32.dll", EntryPoint="CreatePen", CallingConvention=CallingConvention.StdCall)]
3498                 internal extern static IntPtr Win32CreatePen(PenStyle fnPenStyle, int nWidth, ref COLORREF color);
3499
3500                 [DllImport ("gdi32.dll", EntryPoint="CreatePen", CallingConvention=CallingConvention.StdCall)]
3501                 internal extern static IntPtr Win32CreatePen(PenStyle fnPenStyle, int nWidth, IntPtr color);
3502
3503                 [DllImport ("gdi32.dll", EntryPoint="GetStockObject", CallingConvention=CallingConvention.StdCall)]
3504                 internal extern static IntPtr Win32GetStockObject(StockObject fnObject);
3505
3506                 [DllImport ("gdi32.dll", EntryPoint="CreateHatchBrush", CallingConvention=CallingConvention.StdCall)]
3507                 internal extern static IntPtr Win32CreateHatchBrush(HatchStyle fnStyle, IntPtr color);
3508
3509                 [DllImport ("gdi32.dll", EntryPoint="CreateHatchBrush", CallingConvention=CallingConvention.StdCall)]
3510                 internal extern static IntPtr Win32CreateHatchBrush(HatchStyle fnStyle, ref COLORREF color);
3511
3512                 [DllImport("gdi32.dll", EntryPoint = "ExcludeClipRect", CallingConvention = CallingConvention.StdCall)]
3513                 internal extern static int Win32ExcludeClipRect (IntPtr hdc, int left, int top,  int right, int bottom);
3514
3515                 [DllImport ("gdi32.dll", EntryPoint="ExtSelectClipRgn", CallingConvention=CallingConvention.StdCall)]
3516                 internal extern static int Win32ExtSelectClipRgn(IntPtr hdc, IntPtr hrgn, int mode);
3517
3518                 [DllImport ("winmm.dll", EntryPoint="PlaySoundW", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Unicode)]
3519                 internal extern static IntPtr Win32PlaySound(string pszSound, IntPtr hmod, SndFlags fdwSound);
3520
3521                 [DllImport ("user32.dll", EntryPoint="GetDoubleClickTime", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Unicode)]
3522                 private extern static int Win32GetDoubleClickTime ();
3523
3524                 [DllImport ("user32.dll", EntryPoint="SetWindowRgn", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Unicode)]
3525                 internal extern static int Win32SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool redraw);
3526
3527                 [DllImport ("user32.dll", EntryPoint="GetWindowRgn", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Unicode)]
3528                 internal extern static IntPtr Win32GetWindowRgn(IntPtr hWnd, IntPtr hRgn);
3529
3530                 [DllImport ("user32.dll", EntryPoint="ClipCursor", CallingConvention=CallingConvention.StdCall)]
3531                 internal extern static bool Win32ClipCursor (ref RECT lpRect);
3532
3533                 [DllImport ("user32.dll", EntryPoint="GetClipCursor", CallingConvention=CallingConvention.StdCall)]
3534                 internal extern static bool Win32GetClipCursor (out RECT lpRect);
3535
3536                 [DllImport ("gdi32.dll", EntryPoint="BitBlt", CallingConvention=CallingConvention.StdCall)]
3537                 internal static extern bool Win32BitBlt (IntPtr hObject, int nXDest, int nYDest, int nWidth,
3538                    int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
3539
3540                 [DllImport ("gdi32.dll", EntryPoint="CreateCompatibleDC", CallingConvention=CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
3541                 internal static extern IntPtr Win32CreateCompatibleDC (IntPtr hdc);
3542
3543                 [DllImport ("gdi32.dll", EntryPoint="DeleteDC", CallingConvention=CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)]
3544                 internal static extern bool Win32DeleteDC (IntPtr hdc);
3545
3546                 [DllImport ("gdi32.dll", EntryPoint="CreateCompatibleBitmap", CallingConvention=CallingConvention.StdCall)]
3547                 internal static extern IntPtr Win32CreateCompatibleBitmap (IntPtr hdc, int nWidth, int nHeight);
3548
3549                 [DllImport ("kernel32.dll", EntryPoint = "GetSystemPowerStatus", CallingConvention = CallingConvention.StdCall)]
3550                 internal static extern Boolean Win32GetSystemPowerStatus (SYSTEMPOWERSTATUS sps);
3551                 #endregion
3552         }
3553 }