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