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