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