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