/ src / modules / MouseWithoutBorders / App / Helper / NativeMethods.cs
NativeMethods.cs
  1  // Copyright (c) Microsoft Corporation
  2  // The Microsoft Corporation licenses this file to you under the MIT license.
  3  // See the LICENSE file in the project root for more information.
  4  
  5  // <summary>
  6  //     Windows APIs.
  7  // </summary>
  8  // <history>
  9  //     2008 created by Truong Do (ductdo).
 10  //     2009-... modified by Truong Do (TruongDo).
 11  //     2023- Included in PowerToys.
 12  // </history>
 13  using System;
 14  using System.Diagnostics.CodeAnalysis;
 15  using System.Drawing;
 16  using System.Runtime.InteropServices;
 17  using System.Text;
 18  
 19  // We are sure we dont have managed resource in KEYBDINPUT, IntPtr just holds a value
 20  [module: SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable", Scope = "type", Target = "MouseWithoutBorders.NativeMethods+KEYBDINPUT", Justification = "Dotnet port with style preservation")]
 21  
 22  // Some other minor issues
 23  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#ConvertStringSidToSid(System.String,System.IntPtr&)", MessageId = "0", Justification = "Dotnet port with style preservation")]
 24  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#DrawText(System.IntPtr,System.String,System.Int32,MouseWithoutBorders.NativeMethods+RECT&,System.UInt32)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 25  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#SetWindowText(System.IntPtr,System.String)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 26  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#FindWindow(System.String,System.String)", MessageId = "0", Justification = "Dotnet port with style preservation")]
 27  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#FindWindow(System.String,System.String)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 28  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#GetWindowText(System.IntPtr,System.Text.StringBuilder,System.Int32)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 29  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#keybd_event(System.Byte,System.Byte,System.UInt32,System.Int32)", MessageId = "3", Justification = "Dotnet port with style preservation")]
 30  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#SendMessage(System.IntPtr,System.Int32,System.IntPtr,System.IntPtr)", MessageId = "return", Justification = "Dotnet port with style preservation")]
 31  [module: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "MouseWithoutBorders.NativeMethods+KEYBDINPUT.#dwExtraInfo", Justification = "Dotnet port with style preservation")]
 32  [module: SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Scope = "member", Target = "MouseWithoutBorders.NativeMethods+INPUT64.#type", Justification = "Dotnet port with style preservation")]
 33  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#TerminateProcess(System.IntPtr,System.IntPtr)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 34  [module: SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#GetClassName(System.IntPtr,System.Text.StringBuilder,System.Int32)", MessageId = "1", Justification = "Dotnet port with style preservation")]
 35  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#GetClassName(System.IntPtr,System.Text.StringBuilder,System.Int32)", MessageId = "return", Justification = "Dotnet port with style preservation")]
 36  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#GetAsyncKeyState(System.IntPtr)", MessageId = "0", Justification = "Dotnet port with style preservation")]
 37  [module: SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Scope = "member", Target = "MouseWithoutBorders.NativeMethods.#GetAsyncKeyState(System.IntPtr)", MessageId = "return", Justification = "Dotnet port with style preservation")]
 38  
 39  namespace MouseWithoutBorders
 40  {
 41      internal sealed partial class NativeMethods
 42      {
 43          internal struct IconInfo
 44          {
 45              internal bool fIcon;
 46              internal int xHotspot;
 47              internal int yHotspot;
 48              internal IntPtr hbmMask;
 49              internal IntPtr hbmColor;
 50          }
 51  
 52          [DllImport("user32.dll")]
 53          internal static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
 54  
 55          [DllImport("user32.dll", CharSet = CharSet.Auto)]
 56          [return: MarshalAs(UnmanagedType.Bool)]
 57          internal static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
 58  
 59          [DllImport("user32.dll", CharSet = CharSet.Auto)]
 60          internal static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
 61  
 62          [DllImport("user32.dll")]
 63          internal static extern IntPtr GetForegroundWindow();
 64  
 65          [DllImport("user32.dll")]
 66          [return: MarshalAs(UnmanagedType.Bool)]
 67          internal static extern bool SetForegroundWindow(IntPtr hWnd);
 68  
 69          [DllImport("user32.dll")]
 70          internal static extern IntPtr CreateIconIndirect(ref IconInfo icon);
 71  
 72          [return: MarshalAs(UnmanagedType.Bool)]
 73          [DllImport("user32.dll", SetLastError = true)]
 74          internal static extern bool SetProcessDPIAware();
 75  
 76          [DllImport("Shcore.dll", SetLastError = true)]
 77          internal static extern int SetProcessDpiAwareness(uint type); // Win 8.1 and up, DPI can be per monitor.
 78  
 79          [DllImport("kernel32.dll")]
 80          internal static extern uint WTSGetActiveConsoleSessionId();
 81  
 82          [DllImport("user32.dll", SetLastError = true)]
 83          internal static extern bool ChangeWindowMessageFilterEx(IntPtr hWnd, uint msg, int action, IntPtr changeInfo);
 84  
 85          [DllImport("user32.dll", CharSet = CharSet.Auto)]
 86          [return: MarshalAs(UnmanagedType.Bool)]
 87          internal static extern bool PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
 88  
 89          [DllImport("user32.dll", SetLastError = false)]
 90          internal static extern IntPtr GetDesktopWindow();
 91  
 92          [DllImport("user32.dll")]
 93          internal static extern IntPtr GetWindowDC(IntPtr hWnd);
 94  
 95          [DllImport("user32.dll")]
 96          internal static extern int DrawText(IntPtr hDC, string lpString, int nCount, ref RECT lpRect, uint uFormat);
 97  
 98          [DllImport("gdi32.dll")]
 99          internal static extern uint SetTextColor(IntPtr hdc, int crColor);
100  
101          [DllImport("gdi32.dll")]
102          internal static extern uint SetBkColor(IntPtr hdc, int crColor);
103  
104          [DllImport("user32.dll")]
105          internal static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
106  
107          [DllImport("user32.dll", CharSet = CharSet.Auto)]
108          internal static extern IntPtr GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
109  
110          [DllImport("user32.dll")]
111          [return: MarshalAs(UnmanagedType.Bool)]
112          internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
113  
114          [DllImport("user32.dll")]
115          [return: MarshalAs(UnmanagedType.Bool)]
116          internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
117  
118          [DllImport("user32.dll", SetLastError = true)]
119          internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
120  
121          [DllImport("user32.dll")]
122          [return: MarshalAs(UnmanagedType.Bool)]
123          internal static extern bool SetWindowText(IntPtr hWnd, string lpString);
124  
125          [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
126          internal static extern int GetWindowTextLength(IntPtr hWnd);
127  
128          [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
129          internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
130  
131          [DllImport("user32.dll", CharSet = CharSet.Auto)]
132          [return: MarshalAs(UnmanagedType.Bool)]
133          internal static extern bool DestroyIcon(IntPtr handle);
134  
135          [DllImport("user32")]
136          [return: MarshalAs(UnmanagedType.Bool)]
137          internal static extern bool SetCursorPos(int X, int Y);
138  
139          [DllImport("user32", SetLastError = true)]
140          [return: MarshalAs(UnmanagedType.Bool)]
141          internal static extern bool GetCursorPos(ref Point p);
142  
143          [DllImport("advapi32", SetLastError = true)]
144          [return: MarshalAs(UnmanagedType.Bool)]
145          internal static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);
146  
147          [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
148          [return: MarshalAs(UnmanagedType.Bool)]
149          internal static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
150  
151          [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
152          [return: MarshalAs(UnmanagedType.Bool)]
153          internal static extern bool DuplicateTokenEx(
154              IntPtr ExistingTokenHandle,
155              uint dwDesiredAccess,
156              ref SECURITY_ATTRIBUTES lpThreadAttributes,
157              int TokenType,
158              int ImpersonationLevel,
159              ref IntPtr DuplicateTokenHandle);
160  
161          [DllImport("advapi32.dll", SetLastError = true)]
162          [return: MarshalAs(UnmanagedType.Bool)]
163          internal static extern bool ConvertStringSidToSid(string StringSid, out IntPtr ptrSid);
164  
165          [DllImport("advapi32.dll", SetLastError = true)]
166          [return: MarshalAs(UnmanagedType.Bool)]
167          internal static extern bool SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref TOKEN_MANDATORY_LABEL TokenInformation, uint TokenInformationLength);
168  
169          [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", Justification = "Dotnet port with style preservation")]
170          [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
171          [return: MarshalAs(UnmanagedType.Bool)]
172          internal static extern bool CreateProcessAsUser(
173              IntPtr hToken,
174              string lpApplicationName,
175              string lpCommandLine,
176              ref SECURITY_ATTRIBUTES lpProcessAttributes,
177              ref SECURITY_ATTRIBUTES lpThreadAttributes,
178              [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
179              int dwCreationFlags,
180              IntPtr lpEnvironment,
181              string lpCurrentDirectory,
182              ref STARTUPINFO lpStartupInfo,
183              out PROCESS_INFORMATION lpProcessInformation);
184  
185          [DllImport("user32.dll")]
186          [return: MarshalAs(UnmanagedType.Bool)]
187          internal static extern bool EnumDisplayMonitors(
188              IntPtr hdc,
189              IntPtr lprcClip,
190              EnumMonitorsDelegate lpfnEnum,
191              IntPtr dwData);
192  
193          [DllImport("user32.dll")]
194          [return: MarshalAs(UnmanagedType.Bool)]
195          internal static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
196  
197          [DllImport("User32.dll")]
198          internal static extern int FindWindow(string ClassName, string WindowName);
199  
200          [DllImport("kernel32.dll")]
201          internal static extern uint GetCurrentThreadId();
202  
203          [DllImport("user32.dll", SetLastError = true)]
204          internal static extern IntPtr GetThreadDesktop(uint dwThreadId);
205  
206          [DllImport("user32.dll")]
207          internal static extern short GetAsyncKeyState(IntPtr vKey);
208  
209          [DllImport("user32.dll", SetLastError = true)]
210          internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
211  
212          [StructLayout(LayoutKind.Sequential)]
213          internal struct POINT
214          {
215              internal int x;
216              internal int y;
217          }
218  
219          [StructLayout(LayoutKind.Sequential)]
220          internal struct CURSORINFO
221          {
222              public int cbSize;
223              public int flags;
224              public IntPtr hCursor;
225              public POINT ptScreenPos;
226          }
227  
228          [DllImport("user32.dll")]
229          internal static extern bool GetCursorInfo(out CURSORINFO ci);
230  
231          [DllImport("user32.dll", SetLastError = true)]
232          [return: MarshalAs(UnmanagedType.Bool)]
233          internal static extern bool AddClipboardFormatListener(IntPtr hwnd);
234  
235          [DllImport("user32.dll", SetLastError = true)]
236          [return: MarshalAs(UnmanagedType.Bool)]
237          internal static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
238  
239  #if USE_GetSecurityDescriptorSacl
240          internal enum SE_OBJECT_TYPE
241          {
242              SE_UNKNOWN_OBJECT_TYPE = 0,
243              SE_FILE_OBJECT,
244              SE_SERVICE,
245              SE_PRINTER,
246              SE_REGISTRY_KEY,
247              SE_LMSHARE,
248              SE_KERNEL_OBJECT,
249              SE_WINDOW_OBJECT,
250              SE_DS_OBJECT,
251              SE_DS_OBJECT_ALL,
252              SE_PROVIDER_DEFINED_OBJECT,
253              SE_WMIGUID_OBJECT,
254              SE_REGISTRY_WOW64_32KEY
255          }
256  
257          [Flags]
258          internal enum SECURITY_INFORMATION : uint
259          {
260              LABEL_SECURITY_INFORMATION = 0x00000010
261          }
262  
263          [StructLayoutAttribute(LayoutKind.Explicit)]
264          internal struct SECURITY_DESCRIPTOR
265          {
266              [FieldOffset(0)]
267              public byte revision;
268  
269              [FieldOffset(1)]
270              public byte size;
271  
272              [FieldOffset(2)]
273              public short control;
274  
275              [FieldOffset(4)]
276              public IntPtr owner;
277  
278              [FieldOffset(8)]
279              public IntPtr group;
280  
281              [FieldOffset(12)]
282              public IntPtr sacl;
283  
284              [FieldOffset(16)]
285              public IntPtr dacl;
286          }
287  
288          [StructLayout(LayoutKind.Sequential)]
289          internal struct ACL { public byte AclRevision; public byte Sbz1; public int AclSize; public int AceCount; public int Sbz2; } 
290  
291          [DllImport("advapi32", SetLastError = true)]
292          [return: MarshalAs(UnmanagedType.Bool)]
293          internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string StringSecurityDescriptor,
294          UInt32 StringSDRevision, out SECURITY_DESCRIPTOR SecurityDescriptor, out UInt64 SecurityDescriptorSize);
295  
296          [DllImport("advapi32.dll", SetLastError = true)]
297          internal static extern int GetSecurityDescriptorSacl([MarshalAs(UnmanagedType.Struct)] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int lpbSaclPresent, [MarshalAs(UnmanagedType.Struct)] ref ACL pSacl, int lpbSaclDefaulted); 
298  
299          [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
300          internal static extern uint SetNamedSecurityInfo(
301              string pObjectName,
302              SE_OBJECT_TYPE ObjectType,
303              SECURITY_INFORMATION SecurityInfo,
304              IntPtr psidOwner,
305              IntPtr psidGroup,
306              IntPtr pDacl,
307              IntPtr pSacl);
308  #endif
309  
310  #if SINGLE_PROCESS
311          [DllImport("user32.dll", SetLastError = true)]
312          [return: MarshalAs(UnmanagedType.Bool)]
313          internal static extern bool SetThreadDesktop(IntPtr hDesktop);
314  #endif
315  
316          [DllImport("user32.dll", SetLastError = true)]
317          internal static extern IntPtr OpenInputDesktop(uint dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fInherit, uint dwDesiredAccess);
318  
319          [DllImport("user32.dll", SetLastError = true)]
320          [return: MarshalAs(UnmanagedType.Bool)]
321          internal static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex, [Out] byte[] pvInfo, int nLength, out uint lpnLengthNeeded);
322  
323          [DllImport("gdi32.dll")]
324          internal static extern uint SetPixel(IntPtr hdc, int X, int Y, uint crColor);
325  
326          internal const int WM_SHOW_DRAG_DROP = 0x400;
327          internal const int WM_HIDE_DRAG_DROP = 0x401;
328          internal const int WM_CHECK_EXPLORER_DRAG_DROP = 0x402;
329          internal const int WM_QUIT = 0x403;
330          internal const int WM_SWITCH = 0x404;
331          internal const int WM_HIDE_DD_HELPER = 0x405;
332          internal const int WM_SHOW_SETTINGS_FORM = 0x406;
333  
334          internal static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
335  
336          // internal static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
337          // internal static readonly IntPtr HWND_TOP = new IntPtr(0);
338          // internal static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
339          internal const uint SWP_NOSIZE = 0x0001;
340          internal const uint SWP_NOMOVE = 0x0002;
341          internal const uint SWP_NOZORDER = 0x0004;
342          internal const uint SWP_NOREDRAW = 0x0008;
343          internal const uint SWP_SHOWWINDOW = 0x0040;
344          internal const uint SWP_HIDEWINDOW = 0x0080;
345  
346          internal const int UOI_FLAGS = 1;
347          internal const int UOI_NAME = 2;
348          internal const int UOI_TYPE = 3;
349          internal const int UOI_USER_SID = 4;
350          internal const uint DESKTOP_WRITEOBJECTS = 0x0080;
351          internal const uint DESKTOP_READOBJECTS = 0x0001;
352          internal const uint DF_ALLOWOTHERACCOUNTHOOK = 0x0001;
353  
354          // internal const UInt32 GENERIC_READ                     = 0x80000000;
355          internal const uint GENERIC_WRITE = 0x40000000;
356  
357          // internal const UInt32 GENERIC_EXECUTE                  = 0x20000000;
358          internal const uint GENERIC_ALL = 0x10000000;
359  
360          [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
361          internal struct RECT
362          {
363              internal int Left;
364              internal int Top;
365              internal int Right;
366              internal int Bottom;
367          }
368  
369          // size of a device name string
370          internal const int CCHDEVICENAME = 32;
371  
372          [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
373          internal struct MonitorInfoEx
374          {
375              internal int cbSize;
376              internal RECT rcMonitor;
377              internal RECT rcWork;
378              internal uint dwFlags;
379  
380              // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
381              // internal string szDeviceName;
382          }
383  
384          // We are WOW
385          [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Justification = "Dotnet port with style preservation")]
386          [DllImport(
387              "user32.dll",
388              CharSet = CharSet.Auto,
389              CallingConvention = CallingConvention.StdCall,
390              SetLastError = true)]
391          internal static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
392  
393          [DllImport(
394              "user32.dll",
395              CharSet = CharSet.Auto,
396              CallingConvention = CallingConvention.StdCall,
397              SetLastError = true)]
398          internal static extern int UnhookWindowsHookEx(int idHook);
399  
400          // In X64, we are running WOW
401          [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", Justification = "Dotnet port with style preservation")]
402          [DllImport(
403              "user32.dll",
404              CharSet = CharSet.Auto,
405              CallingConvention = CallingConvention.StdCall)]
406          internal static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
407  
408          internal enum InputType
409          {
410              INPUT_MOUSE = 0,
411              INPUT_KEYBOARD = 1,
412              INPUT_HARDWARE = 2,
413          }
414  
415          [Flags]
416          internal enum MOUSEEVENTF
417          {
418              MOVE = 0x0001,
419              LEFTDOWN = 0x0002,
420              LEFTUP = 0x0004,
421              RIGHTDOWN = 0x0008,
422              RIGHTUP = 0x0010,
423              MIDDLEDOWN = 0x0020,
424              MIDDLEUP = 0x0040,
425              XDOWN = 0x0080,
426              XUP = 0x0100,
427              WHEEL = 0x0800,
428              VIRTUALDESK = 0x4000,
429              ABSOLUTE = 0x8000,
430          }
431  
432          [Flags]
433          internal enum KEYEVENTF
434          {
435              KEYDOWN = 0x0000,
436              EXTENDEDKEY = 0x0001,
437              KEYUP = 0x0002,
438              UNICODE = 0x0004,
439              SCANCODE = 0x0008,
440          }
441  
442          // http://msdn.microsoft.com/en-us/library/ms646273(VS.85).aspx
443          [StructLayout(LayoutKind.Sequential)]
444          internal struct MOUSEINPUT
445          {
446              internal int dx;
447              internal int dy;
448              internal int mouseData;
449              internal int dwFlags;
450              internal int time;
451              internal IntPtr dwExtraInfo;
452          }
453  
454          [StructLayout(LayoutKind.Sequential)]
455          internal struct KEYBDINPUT
456          {
457              internal short wVk;
458              internal short wScan;
459              internal int dwFlags;
460              internal int time;
461              internal IntPtr dwExtraInfo;
462          }
463  
464          [StructLayout(LayoutKind.Sequential)]
465          internal struct HARDWAREINPUT
466          {
467              internal int uMsg;
468              internal short wParamL;
469              internal short wParamH;
470          }
471  
472          [SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", Justification = "Dotnet port with style preservation")]
473          [StructLayout(LayoutKind.Explicit)]
474          internal struct INPUT
475          {
476              [FieldOffset(0)]
477              internal int type;
478  
479              [FieldOffset(4)]
480              internal MOUSEINPUT mi;
481  
482              [FieldOffset(4)]
483              internal KEYBDINPUT ki;
484          }
485  
486          [StructLayout(LayoutKind.Explicit)]
487          internal struct INPUT64
488          {
489              [FieldOffset(0)]
490              internal int type;
491  
492              [FieldOffset(8)]
493              internal MOUSEINPUT mi;
494  
495              [FieldOffset(8)]
496              internal KEYBDINPUT ki;
497          }
498  
499          [DllImport("user32.dll", EntryPoint = "SendInput", SetLastError = true)]
500          internal static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
501  
502          [DllImport("user32.dll", EntryPoint = "SendInput", SetLastError = true)]
503          internal static extern uint SendInput64(uint nInputs, INPUT64[] pInputs, int cbSize);
504  
505          [DllImport("user32.dll", EntryPoint = "GetMessageExtraInfo", SetLastError = true)]
506          internal static extern IntPtr GetMessageExtraInfo();
507  
508          [DllImport("user32.dll", EntryPoint = "LockWorkStation", SetLastError = true)]
509          internal static extern uint LockWorkStation();
510  
511          // [DllImport("user32.dll")]
512          // internal static extern void keybd_event(byte bVk, byte bScan, UInt32 dwFlags, int dwExtraInfo);
513          [DllImport("user32.dll")]
514          internal static extern uint MapVirtualKey(uint uCode, uint uMapType);
515  
516          [StructLayout(LayoutKind.Sequential)]
517          internal struct LUID
518          {
519              internal int LowPart;
520              internal int HighPart;
521          }// end struct
522  
523          [StructLayout(LayoutKind.Sequential)]
524          internal struct LUID_AND_ATTRIBUTES
525          {
526              internal LUID Luid;
527              internal int Attributes;
528          }// end struct
529  
530          [StructLayout(LayoutKind.Sequential)]
531          internal struct TOKEN_PRIVILEGES
532          {
533              internal int PrivilegeCount;
534  
535              // LUID_AND_ATTRIBUTES
536              [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
537              internal int[] Privileges;
538          }
539  
540          internal const int READ_CONTROL = 0x00020000;
541  
542          internal const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
543  
544          internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
545          internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
546          internal const int STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
547  
548          internal const int STANDARD_RIGHTS_ALL = 0x001F0000;
549  
550          internal const int SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
551  
552          internal const int TOKEN_IMPERSONATE = 0x0004;
553          internal const int TOKEN_QUERY_SOURCE = 0x0010;
554          internal const int TOKEN_ADJUST_PRIVILEGES = 0x0020;
555          internal const int TOKEN_ADJUST_GROUPS = 0x0040;
556          internal const int TOKEN_ADJUST_SESSIONID = 0x0100;
557  
558          internal const int TOKEN_ALL_ACCESS_P = STANDARD_RIGHTS_REQUIRED |
559                                        TOKEN_ASSIGN_PRIMARY |
560                                        TOKEN_DUPLICATE |
561                                        TOKEN_IMPERSONATE |
562                                        TOKEN_QUERY |
563                                        TOKEN_QUERY_SOURCE |
564                                        TOKEN_ADJUST_PRIVILEGES |
565                                        TOKEN_ADJUST_GROUPS |
566                                        TOKEN_ADJUST_DEFAULT;
567  
568          internal const int TOKEN_ALL_ACCESS = TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID;
569  
570          internal const int TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;
571  
572          internal const int TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
573                                        TOKEN_ADJUST_PRIVILEGES |
574                                        TOKEN_ADJUST_GROUPS |
575                                        TOKEN_ADJUST_DEFAULT;
576  
577          internal const int TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE;
578  
579          internal const int CREATE_NEW_PROCESS_GROUP = 0x00000200;
580          internal const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
581  
582          internal const int IDLE_PRIORITY_CLASS = 0x40;
583          internal const int NORMAL_PRIORITY_CLASS = 0x20;
584          internal const int HIGH_PRIORITY_CLASS = 0x80;
585          internal const int REALTIME_PRIORITY_CLASS = 0x100;
586  
587          internal const int CREATE_NEW_CONSOLE = 0x00000010;
588  
589          internal const string SE_DEBUG_NAME = "SeDebugPrivilege";
590          internal const string SE_RESTORE_NAME = "SeRestorePrivilege";
591          internal const string SE_BACKUP_NAME = "SeBackupPrivilege";
592  
593          internal const int SE_PRIVILEGE_ENABLED = 0x0002;
594  
595          internal const int ERROR_NOT_ALL_ASSIGNED = 1300;
596  
597          [StructLayout(LayoutKind.Sequential)]
598          internal struct PROCESSENTRY32
599          {
600              internal uint dwSize;
601              internal uint cntUsage;
602              internal uint th32ProcessID;
603              internal IntPtr th32DefaultHeapID;
604              internal uint th32ModuleID;
605              internal uint cntThreads;
606              internal uint th32ParentProcessID;
607              internal int pcPriClassBase;
608              internal uint dwFlags;
609              [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
610              internal string szExeFile;
611          }
612  
613          internal const uint TH32CS_SNAPPROCESS = 0x00000002;
614  
615          // internal static int INVALID_HANDLE_VALUE = -1;
616          [DllImport("kernel32.dll", SetLastError = true)]
617          [return: MarshalAs(UnmanagedType.Bool)]
618          internal static extern bool CloseHandle(IntPtr hSnapshot);
619  
620          [StructLayout(LayoutKind.Sequential)]
621          internal struct SECURITY_ATTRIBUTES
622          {
623              internal int Length;
624              internal IntPtr lpSecurityDescriptor;
625              internal bool bInheritHandle;
626          }
627  
628          [StructLayout(LayoutKind.Sequential)]
629          internal struct PROCESS_INFORMATION
630          {
631              internal IntPtr hProcess;
632              internal IntPtr hThread;
633              internal uint dwProcessId;
634              internal uint dwThreadId;
635          }
636  
637          [StructLayout(LayoutKind.Sequential)]
638          internal struct STARTUPINFO
639          {
640              internal int cb;
641              internal string lpReserved;
642              internal string lpDesktop;
643              internal string lpTitle;
644              internal uint dwX;
645              internal uint dwY;
646              internal uint dwXSize;
647              internal uint dwYSize;
648              internal uint dwXCountChars;
649              internal uint dwYCountChars;
650              internal uint dwFillAttribute;
651              internal uint dwFlags;
652              internal short wShowWindow;
653              internal short cbReserved2;
654              internal IntPtr lpReserved2;
655              internal IntPtr hStdInput;
656              internal IntPtr hStdOutput;
657              internal IntPtr hStdError;
658          }
659  
660          [StructLayout(LayoutKind.Sequential)]
661          internal struct SID_AND_ATTRIBUTES
662          {
663              internal IntPtr Sid;
664              internal int Attributes;
665          }
666  
667          [StructLayout(LayoutKind.Sequential)]
668          internal struct TOKEN_MANDATORY_LABEL
669          {
670              internal SID_AND_ATTRIBUTES Label;
671          }
672  
673          internal const int TOKEN_DUPLICATE = 0x0002;
674          internal const int TOKEN_QUERY = 0x0008;
675          internal const int TOKEN_ADJUST_DEFAULT = 0x0080;
676          internal const int TOKEN_ASSIGN_PRIMARY = 0x0001;
677          internal const uint MAXIMUM_ALLOWED = 0x2000000;
678          internal const int SE_GROUP_INTEGRITY = 0x00000020;
679  
680          internal enum SECURITY_IMPERSONATION_LEVEL : int
681          {
682              SecurityAnonymous = 0,
683              SecurityIdentification = 1,
684              SecurityImpersonation = 2,
685              SecurityDelegation = 3,
686          }
687  
688          internal enum TOKEN_TYPE : int
689          {
690              TokenPrimary = 1,
691              TokenImpersonation = 2,
692          }
693  
694          internal enum TOKEN_INFORMATION_CLASS : int
695          {
696              TokenUser = 1,
697              TokenGroups,
698              TokenPrivileges,
699              TokenOwner,
700              TokenPrimaryGroup,
701              TokenDefaultDacl,
702              TokenSource,
703              TokenType,
704              TokenImpersonationLevel,
705              TokenStatistics,
706              TokenRestrictedSids,
707              TokenSessionId,
708              TokenGroupsAndPrivileges,
709              TokenSessionReference,
710              TokenSandBoxInert,
711              TokenAuditPolicy,
712              TokenOrigin,
713              TokenElevationType,
714              TokenLinkedToken,
715              TokenElevation,
716              TokenHasRestrictions,
717              TokenAccessInformation,
718              TokenVirtualizationAllowed,
719              TokenVirtualizationEnabled,
720              TokenIntegrityLevel,
721              TokenUIAccess,
722              TokenMandatoryPolicy,
723              TokenLogonSid,
724              MaxTokenInfoClass,
725          }
726  
727          // [DllImport("kernel32.dll")]
728          // internal static extern int Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
729  
730          // [DllImport("kernel32.dll")]
731          // internal static extern int Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
732  
733          // [DllImport("kernel32.dll", SetLastError = true)]
734          // internal static extern IntPtr CreateToolhelp32Snapshot(UInt32 dwFlags, UInt32 th32ProcessID);
735          [DllImport("Wtsapi32.dll")]
736          internal static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken);
737  
738          [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "1", Justification = "Dotnet port with style preservation")]
739          [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
740          [return: MarshalAs(UnmanagedType.Bool)]
741          internal static extern bool LookupPrivilegeValue(IntPtr lpSystemName, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
742  
743          // [DllImport("kernel32.dll")]
744          // [return: MarshalAs(UnmanagedType.Bool)]
745          // static extern bool ProcessIdToSessionId(UInt32 dwProcessId, ref UInt32 pSessionId);
746          [DllImport("kernel32.dll")]
747          internal static extern IntPtr OpenProcess(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
748  
749          [DllImport("advapi32.dll", SetLastError = true)]
750          [return: MarshalAs(UnmanagedType.Bool)]
751          internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
752  
753          [DllImport("userenv.dll", SetLastError = true)]
754          [return: MarshalAs(UnmanagedType.Bool)]
755          internal static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, [MarshalAs(UnmanagedType.Bool)] bool bInherit);
756  
757          [DllImport("advapi32.dll", SetLastError = true)]
758          [return: MarshalAs(UnmanagedType.Bool)]
759          internal static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
760  
761          [DllImport("advapi32.dll", SetLastError = true)]
762          [return: MarshalAs(UnmanagedType.Bool)]
763          internal static extern bool RevertToSelf();
764  
765          internal delegate bool EnumMonitorsDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref NativeMethods.RECT lprcMonitor, IntPtr dwData);
766  
767          internal delegate int HookProc(int nCode, int wParam, IntPtr lParam);
768  
769          [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
770          internal sealed class MEMORYSTATUSEX
771          {
772              public uint dwLength;
773              public uint dwMemoryLoad;
774              public ulong ullTotalPhys;
775              public ulong ullAvailPhys;
776              public ulong ullTotalPageFile;
777              public ulong ullAvailPageFile;
778              public ulong ullTotalVirtual;
779              public ulong ullAvailVirtual;
780              public ulong ullAvailExtendedVirtual;
781  
782              public MEMORYSTATUSEX()
783              {
784                  this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
785              }
786          }
787  
788          [return: MarshalAs(UnmanagedType.Bool)]
789          [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
790          internal static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
791  
792          /*
793          [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
794          internal extern static int NetUserGetInfo([MarshalAs(UnmanagedType.LPWStr)] string ServerName,
795              [MarshalAs(UnmanagedType.LPWStr)] string UserName, int level,out IntPtr BufPtr);
796  
797          [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
798          internal struct USER_INFO_10
799          {
800              [MarshalAs(UnmanagedType.LPWStr)]
801              public string usri10_name;
802              [MarshalAs(UnmanagedType.LPWStr)]
803              public string usri10_comment;
804              [MarshalAs(UnmanagedType.LPWStr)]
805              public string usri10_usr_comment;
806              [MarshalAs(UnmanagedType.LPWStr)]
807              public string usri10_full_name;
808          }
809  
810          [DllImport("Netapi32.dll", SetLastError = true)]
811          internal static extern int NetApiBufferFree(IntPtr Buffer);
812          */
813  
814          internal enum EXTENDED_NAME_FORMAT
815          {
816              NameUnknown = 0,
817              NameFullyQualifiedDN = 1,
818              NameSamCompatible = 2,
819              NameDisplay = 3,
820              NameUniqueId = 6,
821              NameCanonical = 7,
822              NameUserPrincipal = 8,
823              NameCanonicalEx = 9,
824              NameServicePrincipal = 10,
825              NameDnsDomain = 12,
826          }
827  
828          [DllImport("secur32.dll", CharSet = CharSet.Unicode)]
829          [return: MarshalAs(UnmanagedType.I1)]
830          internal static extern bool GetUserNameEx(int nameFormat, StringBuilder userName, ref uint userNameSize);
831  
832          [DllImport("Shcore.dll", SetLastError = true)]
833          internal static extern int GetDpiForMonitor(IntPtr hMonitor, uint dpiType, out uint dpiX, out uint dpiY);
834  
835          private static string GetDNSDomain()
836          {
837              if (Environment.OSVersion.Platform != PlatformID.Win32NT)
838              {
839                  return null;
840              }
841  
842              StringBuilder userName = new StringBuilder(1024);
843              uint userNameSize = (uint)userName.Capacity;
844  
845              if (GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameDnsDomain, userName, ref userNameSize))
846              {
847                  string[] nameParts = userName.ToString().Split('\\');
848                  if (nameParts.Length != 2)
849                  {
850                      return null;
851                  }
852  
853                  return nameParts[0];
854              }
855  
856              return null;
857          }
858  
859          /// <summary>
860          /// Use this method to figure out if your code is running on a Microsoft computer.
861          /// </summary>
862          internal static bool IsRunningAtMicrosoft()
863          {
864              string domain = GetDNSDomain();
865  
866              if (!string.IsNullOrEmpty(domain) && domain.EndsWith("microsoft.com", true, System.Globalization.CultureInfo.CurrentCulture))
867              {
868                  return true;
869              }
870  
871              return false;
872          }
873      }
874  }