From da79bc74e22ba8ebc77940f3dd445104712af799 Mon Sep 17 00:00:00 2001 From: Jared Goodwin Date: Thu, 4 May 2023 11:14:57 -0700 Subject: [PATCH] Move native interop code to new project. --- Agent/Agent.csproj | 1 + Agent/Services/AgentHubConnection.cs | 5 +- .../Services/MacOS/DeviceInfoGeneratorMac.cs | 4 - Agent/Services/Windows/AppLauncherWin.cs | 10 +- .../Windows/DeviceInfoGeneratorWin.cs | 7 +- Remotely.sln | 15 + .../RemoteControlDtos/WindowsSessionsDto.cs | 3 +- Shared/Models/WindowsSession.cs | 24 - Shared/Win32/ADVAPI32.cs | 372 ----- Shared/Win32/GDI32.cs | 81 - Shared/Win32/Kernel32.cs | 86 -- Shared/Win32/SECUR32.cs | 377 ----- Shared/Win32/Shlwapi.cs | 52 - Shared/Win32/User32.cs | 1319 ----------------- Shared/Win32/WTSAPI32.cs | 80 - Shared/Win32/Win32Interop.cs | 230 --- submodules/Immense.RemoteControl | 2 +- 17 files changed, 28 insertions(+), 2640 deletions(-) delete mode 100644 Shared/Models/WindowsSession.cs delete mode 100644 Shared/Win32/ADVAPI32.cs delete mode 100644 Shared/Win32/GDI32.cs delete mode 100644 Shared/Win32/Kernel32.cs delete mode 100644 Shared/Win32/SECUR32.cs delete mode 100644 Shared/Win32/Shlwapi.cs delete mode 100644 Shared/Win32/User32.cs delete mode 100644 Shared/Win32/WTSAPI32.cs delete mode 100644 Shared/Win32/Win32Interop.cs diff --git a/Agent/Agent.csproj b/Agent/Agent.csproj index 57945a43f..365382494 100644 --- a/Agent/Agent.csproj +++ b/Agent/Agent.csproj @@ -40,6 +40,7 @@ + diff --git a/Agent/Services/AgentHubConnection.cs b/Agent/Services/AgentHubConnection.cs index ff0f1432c..a860e658e 100644 --- a/Agent/Services/AgentHubConnection.cs +++ b/Agent/Services/AgentHubConnection.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.SignalR.Client; +using Immense.RemoteControl.Desktop.Native.Windows; +using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Remotely.Agent.Extensions; @@ -6,8 +7,6 @@ using Remotely.Shared.Enums; using Remotely.Shared.Models; using Remotely.Shared.Services; -using Remotely.Shared.Utilities; -using Remotely.Shared.Win32; using System; using System.Collections.Generic; using System.IO; diff --git a/Agent/Services/MacOS/DeviceInfoGeneratorMac.cs b/Agent/Services/MacOS/DeviceInfoGeneratorMac.cs index 098e60ea0..f7471c70f 100644 --- a/Agent/Services/MacOS/DeviceInfoGeneratorMac.cs +++ b/Agent/Services/MacOS/DeviceInfoGeneratorMac.cs @@ -2,12 +2,8 @@ using Remotely.Agent.Interfaces; using Remotely.Shared.Models; using Remotely.Shared.Services; -using Remotely.Shared.Utilities; -using Remotely.Shared.Win32; using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace Remotely.Agent.Services.MacOS diff --git a/Agent/Services/Windows/AppLauncherWin.cs b/Agent/Services/Windows/AppLauncherWin.cs index f00f35eb2..5b24089c5 100644 --- a/Agent/Services/Windows/AppLauncherWin.cs +++ b/Agent/Services/Windows/AppLauncherWin.cs @@ -1,9 +1,9 @@ -using Microsoft.AspNetCore.SignalR.Client; +using Immense.RemoteControl.Desktop.Native.Windows; +using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Logging; using Remotely.Agent.Interfaces; using Remotely.Shared.Models; using Remotely.Shared.Utilities; -using Remotely.Shared.Win32; using System; using System.Collections.Generic; using System.Diagnostics; @@ -42,7 +42,7 @@ public async Task LaunchChatService(string pipeName, string userConnectionI await hubConnection.SendAsync("DisplayMessage", $"Starting chat service.", "Starting chat service.", "bg-success", userConnectionId); if (WindowsIdentity.GetCurrent().IsSystem) { - var result = Win32Interop.OpenInteractiveProcess( + var result = Win32Interop.CreateInteractiveSystemProcess( _rcBinaryPath + $" --mode Chat" + $" --host \"{_connectionInfo.Host}\"" + @@ -114,7 +114,7 @@ await hubConnection.SendAsync("DisplayMessage", userConnectionId); if (WindowsIdentity.GetCurrent().IsSystem) { - var result = Win32Interop.OpenInteractiveProcess( + var result = Win32Interop.CreateInteractiveSystemProcess( _rcBinaryPath + $" --mode Unattended" + $" --host {_connectionInfo.Host}" + @@ -170,7 +170,7 @@ public async Task RestartScreenCaster(List viewerIDs, string sessionId, // Give a little time for session changing, etc. await Task.Delay(1000); - var result = Win32Interop.OpenInteractiveProcess(_rcBinaryPath + + var result = Win32Interop.CreateInteractiveSystemProcess(_rcBinaryPath + $" --mode Unattended" + $" --relaunch true" + $" --host {_connectionInfo.Host}" + diff --git a/Agent/Services/Windows/DeviceInfoGeneratorWin.cs b/Agent/Services/Windows/DeviceInfoGeneratorWin.cs index dda9968da..8b47d8a6f 100644 --- a/Agent/Services/Windows/DeviceInfoGeneratorWin.cs +++ b/Agent/Services/Windows/DeviceInfoGeneratorWin.cs @@ -1,12 +1,9 @@ -using Microsoft.Extensions.Logging; +using Immense.RemoteControl.Desktop.Native.Windows; +using Microsoft.Extensions.Logging; using Remotely.Agent.Interfaces; using Remotely.Shared.Models; -using Remotely.Shared.Utilities; -using Remotely.Shared.Win32; using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace Remotely.Agent.Services.Windows diff --git a/Remotely.sln b/Remotely.sln index 5f27f839b..b1d00fd80 100644 --- a/Remotely.sln +++ b/Remotely.sln @@ -73,6 +73,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Immense.RemoteControl.Share EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Immense.RemoteControl.Desktop", "submodules\Immense.RemoteControl\Immense.RemoteControl.Desktop\Immense.RemoteControl.Desktop.csproj", "{034984DC-4B47-42E9-8648-F258C40C7926}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Immense.RemoteControl.Desktop.Native", "submodules\Immense.RemoteControl\Immense.RemoteControl.Desktop.Native\Immense.RemoteControl.Desktop.Native.csproj", "{7A8378BC-8169-4A33-93C6-47C699C5E74D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -275,6 +277,18 @@ Global {034984DC-4B47-42E9-8648-F258C40C7926}.Release|x64.Build.0 = Release|Any CPU {034984DC-4B47-42E9-8648-F258C40C7926}.Release|x86.ActiveCfg = Release|Any CPU {034984DC-4B47-42E9-8648-F258C40C7926}.Release|x86.Build.0 = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|x64.ActiveCfg = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|x64.Build.0 = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|x86.ActiveCfg = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Debug|x86.Build.0 = Debug|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|Any CPU.Build.0 = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|x64.ActiveCfg = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|x64.Build.0 = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|x86.ActiveCfg = Release|Any CPU + {7A8378BC-8169-4A33-93C6-47C699C5E74D}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -290,6 +304,7 @@ Global {8CBED18D-64A8-44C0-8433-EE14E93B472A} = {48C738FB-359E-43DB-B338-FD7CB1CCF6A8} {FEF0D431-EB2F-4C08-A125-8DF59AFDA525} = {48C738FB-359E-43DB-B338-FD7CB1CCF6A8} {034984DC-4B47-42E9-8648-F258C40C7926} = {48C738FB-359E-43DB-B338-FD7CB1CCF6A8} + {7A8378BC-8169-4A33-93C6-47C699C5E74D} = {48C738FB-359E-43DB-B338-FD7CB1CCF6A8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {EAE10B28-119B-437C-9E68-06F0EE3F968A} diff --git a/Shared/Models/RemoteControlDtos/WindowsSessionsDto.cs b/Shared/Models/RemoteControlDtos/WindowsSessionsDto.cs index 29f8089d3..7ca772243 100644 --- a/Shared/Models/RemoteControlDtos/WindowsSessionsDto.cs +++ b/Shared/Models/RemoteControlDtos/WindowsSessionsDto.cs @@ -1,4 +1,5 @@ -using Remotely.Shared.Enums; +using Immense.RemoteControl.Desktop.Native.DataStructures; +using Remotely.Shared.Enums; using System.Collections.Generic; using System.Runtime.Serialization; diff --git a/Shared/Models/WindowsSession.cs b/Shared/Models/WindowsSession.cs deleted file mode 100644 index 71fb124ac..000000000 --- a/Shared/Models/WindowsSession.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Runtime.Serialization; - -namespace Remotely.Shared.Models -{ - [DataContract] - public enum SessionType - { - Console = 0, - RDP = 1 - } - - [DataContract] - public class WindowsSession - { - [DataMember(Name = "ID")] - public uint ID { get; set; } - [DataMember(Name = "Name")] - public string Name { get; set; } - [DataMember(Name = "Type")] - public SessionType Type { get; set; } - [DataMember(Name = "Username")] - public string Username { get; set; } - } -} diff --git a/Shared/Win32/ADVAPI32.cs b/Shared/Win32/ADVAPI32.cs deleted file mode 100644 index 77d6b5265..000000000 --- a/Shared/Win32/ADVAPI32.cs +++ /dev/null @@ -1,372 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Security; - -namespace Remotely.Shared.Win32 -{ - public static class ADVAPI32 - { - #region Structs - public struct TOKEN_PRIVILEGES - { - public struct LUID - { - public UInt32 LowPart; - public Int32 HighPart; - } - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct LUID_AND_ATTRIBUTES - { - public LUID Luid; - public UInt32 Attributes; - } - public int PrivilegeCount; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = ANYSIZE_ARRAY)] - public LUID_AND_ATTRIBUTES[] Privileges; - } - public class USEROBJECTFLAGS - { - public int fInherit = 0; - public int fReserved = 0; - public int dwFlags = 0; - } - [StructLayout(LayoutKind.Sequential)] - public struct SECURITY_ATTRIBUTES - { - public int Length; - public IntPtr lpSecurityDescriptor; - public bool bInheritHandle; - } - [StructLayout(LayoutKind.Sequential)] - public struct PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public int dwProcessId; - public int dwThreadId; - } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct STARTUPINFO - { - public Int32 cb; - public string lpReserved; - public string lpDesktop; - public string lpTitle; - public Int32 dwX; - public Int32 dwY; - public Int32 dwXSize; - public Int32 dwYSize; - public Int32 dwXCountChars; - public Int32 dwYCountChars; - public Int32 dwFillAttribute; - public Int32 dwFlags; - public Int16 wShowWindow; - public Int16 cbReserved2; - public IntPtr lpReserved2; - public IntPtr hStdInput; - public IntPtr hStdOutput; - public IntPtr hStdError; - } - #endregion - - #region Enums - public enum TOKEN_INFORMATION_CLASS - { - /// -     /// The buffer receives a TOKEN_USER structure that contains the user account of the token. -     /// - TokenUser = 1, - - /// -     /// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token. -     /// - TokenGroups, - - /// -     /// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token. -     /// - TokenPrivileges, - - /// -     /// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects. -     /// - TokenOwner, - - /// -     /// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects. -     /// - TokenPrimaryGroup, - - /// -     /// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects. -     /// - TokenDefaultDacl, - - /// -     /// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information. -     /// - TokenSource, - - /// -     /// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token. -     /// - TokenType, - - /// -     /// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails. -     /// - TokenImpersonationLevel, - - /// -     /// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics. -     /// - TokenStatistics, - - /// -     /// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token. -     /// - TokenRestrictedSids, - - /// -     /// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token. -     /// - TokenSessionId, - - /// -     /// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token. -     /// - TokenGroupsAndPrivileges, - - /// -     /// Reserved. -     /// - TokenSessionReference, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag. -     /// - TokenSandBoxInert, - - /// -     /// Reserved. -     /// - TokenAuditPolicy, - - /// -     /// The buffer receives a TOKEN_ORIGIN value. -     /// - TokenOrigin, - - /// -     /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. -     /// - TokenElevationType, - - /// -     /// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. -     /// - TokenLinkedToken, - - /// -     /// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated. -     /// - TokenElevation, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token has ever been filtered. -     /// - TokenHasRestrictions, - - /// -     /// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token. -     /// - TokenAccessInformation, - - /// -     /// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token. -     /// - TokenVirtualizationAllowed, - - /// -     /// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token. -     /// - TokenVirtualizationEnabled, - - /// -     /// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level. -     /// - TokenIntegrityLevel, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set. -     /// - TokenUIAccess, - - /// -     /// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy. -     /// - TokenMandatoryPolicy, - - /// -     /// The buffer receives the token's logon security identifier (SID). -     /// - TokenLogonSid, - - /// -     /// The maximum value for this enumeration -     /// - MaxTokenInfoClass - } - public enum LOGON_TYPE - { - LOGON32_LOGON_INTERACTIVE = 2, - LOGON32_LOGON_NETWORK, - LOGON32_LOGON_BATCH, - LOGON32_LOGON_SERVICE, - LOGON32_LOGON_UNLOCK = 7, - LOGON32_LOGON_NETWORK_CLEARTEXT, - LOGON32_LOGON_NEW_CREDENTIALS - } - public enum LOGON_PROVIDER - { - LOGON32_PROVIDER_DEFAULT, - LOGON32_PROVIDER_WINNT35, - LOGON32_PROVIDER_WINNT40, - LOGON32_PROVIDER_WINNT50 - } - [Flags] - public enum CreateProcessFlags - { - CREATE_BREAKAWAY_FROM_JOB = 0x01000000, - CREATE_DEFAULT_ERROR_MODE = 0x04000000, - CREATE_NEW_CONSOLE = 0x00000010, - CREATE_NEW_PROCESS_GROUP = 0x00000200, - CREATE_NO_WINDOW = 0x08000000, - CREATE_PROTECTED_PROCESS = 0x00040000, - CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, - CREATE_SEPARATE_WOW_VDM = 0x00000800, - CREATE_SHARED_WOW_VDM = 0x00001000, - CREATE_SUSPENDED = 0x00000004, - CREATE_UNICODE_ENVIRONMENT = 0x00000400, - DEBUG_ONLY_THIS_PROCESS = 0x00000002, - DEBUG_PROCESS = 0x00000001, - DETACHED_PROCESS = 0x00000008, - EXTENDED_STARTUPINFO_PRESENT = 0x00080000, - INHERIT_PARENT_AFFINITY = 0x00010000 - } - public enum TOKEN_TYPE : int - { - TokenPrimary = 1, - TokenImpersonation = 2 - } - - public enum SECURITY_IMPERSONATION_LEVEL : int - { - SecurityAnonymous = 0, - SecurityIdentification = 1, - SecurityImpersonation = 2, - SecurityDelegation = 3, - } - - #endregion - - #region Constants - public const int TOKEN_DUPLICATE = 0x0002; - public const uint MAXIMUM_ALLOWED = 0x2000000; - public const int CREATE_NEW_CONSOLE = 0x00000010; - public const int CREATE_NO_WINDOW = 0x08000000; - public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; - public const int STARTF_USESHOWWINDOW = 0x00000001; - public const int DETACHED_PROCESS = 0x00000008; - public const int TOKEN_ALL_ACCESS = 0x000f01ff; - public const int PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF; - public const int STANDARD_RIGHTS_REQUIRED = 0x000F0000; - public const int SYNCHRONIZE = 0x00100000; - - public const int IDLE_PRIORITY_CLASS = 0x40; - public const int NORMAL_PRIORITY_CLASS = 0x20; - public const int HIGH_PRIORITY_CLASS = 0x80; - public const int REALTIME_PRIORITY_CLASS = 0x100; - public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; - public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; - public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; - public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; - public const Int32 ANYSIZE_ARRAY = 1; - - public const int UOI_FLAGS = 1; - public const int UOI_NAME = 2; - public const int UOI_TYPE = 3; - public const int UOI_USER_SID = 4; - public const int UOI_HEAPSIZE = 5; - public const int UOI_IO = 6; - #endregion - - #region DLL Imports - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, - [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, - ref TOKEN_PRIVILEGES newState, - UInt32 bufferLengthInBytes, - ref TOKEN_PRIVILEGES previousState, - out UInt32 returnLengthInBytes); - [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern bool CreateProcessAsUser( - IntPtr hToken, - string lpApplicationName, - string lpCommandLine, - ref SECURITY_ATTRIBUTES lpProcessAttributes, - ref SECURITY_ATTRIBUTES lpThreadAttributes, - bool bInheritHandles, - uint dwCreationFlags, - IntPtr lpEnvironment, - string lpCurrentDirectory, - ref STARTUPINFO lpStartupInfo, - out PROCESS_INFORMATION lpProcessInformation); - - [DllImport("advapi32.dll", SetLastError = true)] - public static extern bool AllocateLocallyUniqueId(out IntPtr pLuid); - - [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = false)] - public static extern SECUR32.WinErrors LsaNtStatusToWinError(SECUR32.WinStatusCodes status); - - [DllImport("advapi32.dll", SetLastError = true)] - public static extern bool GetTokenInformation( - IntPtr TokenHandle, - SECUR32.TOKEN_INFORMATION_CLASS TokenInformationClass, - IntPtr TokenInformation, - uint TokenInformationLength, - out uint ReturnLength); - - [DllImport("advapi32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool LogonUser( - [MarshalAs(UnmanagedType.LPStr)] string pszUserName, - [MarshalAs(UnmanagedType.LPStr)] string pszDomain, - [MarshalAs(UnmanagedType.LPStr)] string pszPassword, - int dwLogonType, - int dwLogonProvider, - out IntPtr phToken); - - [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute] - public static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle); - [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern bool DuplicateTokenEx( - IntPtr hExistingToken, - uint dwDesiredAccess, - ref SECURITY_ATTRIBUTES lpTokenAttributes, - SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, - TOKEN_TYPE TokenType, - out IntPtr phNewToken); - - [DllImport("advapi32.dll", SetLastError = false)] - public static extern uint LsaNtStatusToWinError(uint status); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool GetUserObjectInformationW(IntPtr hObj, int nIndex, - [Out] byte[] pvInfo, uint nLength, out uint lpnLengthNeeded); - #endregion - - - } -} diff --git a/Shared/Win32/GDI32.cs b/Shared/Win32/GDI32.cs deleted file mode 100644 index 46a6ebcd0..000000000 --- a/Shared/Win32/GDI32.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Remotely.Shared.Win32 -{ - public static class GDI32 - { - #region Enums - /// - /// Specifies a raster-operation code. These codes define how the color data for the - /// source rectangle is to be combined with the color data for the destination - /// rectangle to achieve the final color. - /// - public enum TernaryRasterOperations : uint - { - /// dest = source - SRCCOPY = 0x00CC0020, - /// dest = source OR dest - SRCPAINT = 0x00EE0086, - /// dest = source AND dest - SRCAND = 0x008800C6, - /// dest = source XOR dest - SRCINVERT = 0x00660046, - /// dest = source AND (NOT dest) - SRCERASE = 0x00440328, - /// dest = (NOT source) - NOTSRCCOPY = 0x00330008, - /// dest = (NOT src) AND (NOT dest) - NOTSRCERASE = 0x001100A6, - /// dest = (source AND pattern) - MERGECOPY = 0x00C000CA, - /// dest = (NOT source) OR dest - MERGEPAINT = 0x00BB0226, - /// dest = pattern - PATCOPY = 0x00F00021, - /// dest = DPSnoo - PATPAINT = 0x00FB0A09, - /// dest = pattern XOR dest - PATINVERT = 0x005A0049, - /// dest = (NOT dest) - DSTINVERT = 0x00550009, - /// dest = BLACK - BLACKNESS = 0x00000042, - /// dest = WHITE - WHITENESS = 0x00FF0062, - /// - /// Capture window as seen on screen. This includes layered windows - /// such as WPF windows with AllowsTransparency="true" - /// - CAPTUREBLT = 0x40000000 - } - #endregion - - #region DLL Imports - - [DllImport("gdi32.dll", EntryPoint = "BitBlt", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool BitBlt([In] IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, [In] IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop); - - [DllImport("gdi32.dll")] - public static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData); - - [DllImport("GDI32.dll")] - public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);[DllImport("GDI32.dll")] - public static extern IntPtr CreateCompatibleDC(IntPtr hdc); - - [DllImport("GDI32.dll")] - public static extern bool DeleteDC(IntPtr hdc); - - [DllImport("GDI32.dll")] - public static extern bool DeleteObject(IntPtr hObject); - - [DllImport("GDI32.dll")] - public static extern IntPtr GetDeviceCaps(IntPtr hdc, int nIndex); - - [DllImport("GDI32.dll")] - public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); - - #endregion - } -} diff --git a/Shared/Win32/Kernel32.cs b/Shared/Win32/Kernel32.cs deleted file mode 100644 index f7ee6f0ca..000000000 --- a/Shared/Win32/Kernel32.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Remotely.Shared.Win32 -{ - public static class Kernel32 - { - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool CloseHandle(IntPtr hSnapshot); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr GetCommandLine(); - - [return: MarshalAs(UnmanagedType.Bool)] - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer); - - [DllImport("kernel32.dll")] - public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId); - - [DllImport("kernel32.dll")] - public static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId); - - [DllImport("kernel32.dll")] - public static extern uint WTSGetActiveConsoleSessionId(); - /// - /// contains information about the current state of both physical and virtual memory, including extended memory - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public class MEMORYSTATUSEX - { - /// - /// Size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx. - /// - public uint dwLength; - - /// - /// Number between 0 and 100 that specifies the approximate percentage of physical memory that is in use (0 indicates no memory use and 100 indicates full memory use). - /// - public uint dwMemoryLoad; - - /// - /// Total size of physical memory, in bytes. - /// - public ulong ullTotalPhys; - - /// - /// Size of physical memory available, in bytes. - /// - public ulong ullAvailPhys; - - /// - /// Size of the committed memory limit, in bytes. This is physical memory plus the size of the page file, minus a small overhead. - /// - public ulong ullTotalPageFile; - - /// - /// Size of available memory to commit, in bytes. The limit is ullTotalPageFile. - /// - public ulong ullAvailPageFile; - - /// - /// Total size of the user mode portion of the virtual address space of the calling process, in bytes. - /// - public ulong ullTotalVirtual; - - /// - /// Size of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process, in bytes. - /// - public ulong ullAvailVirtual; - - /// - /// Size of unreserved and uncommitted memory in the extended portion of the virtual address space of the calling process, in bytes. - /// - public ulong ullAvailExtendedVirtual; - - /// - /// Initializes a new instance of the class. - /// - public MEMORYSTATUSEX() - { - this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX)); - } - } - } -} diff --git a/Shared/Win32/SECUR32.cs b/Shared/Win32/SECUR32.cs deleted file mode 100644 index 863630e0c..000000000 --- a/Shared/Win32/SECUR32.cs +++ /dev/null @@ -1,377 +0,0 @@ -using Microsoft.Win32.SafeHandles; -using Remotely.Shared.Win32; -using System; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; - -public static class SECUR32 -{ - public enum WinStatusCodes : uint - { - STATUS_SUCCESS = 0 - } - - public enum WinErrors : uint - { - NO_ERROR = 0, - } - public enum WinLogonType - { - LOGON32_LOGON_INTERACTIVE = 2, - LOGON32_LOGON_NETWORK = 3, - LOGON32_LOGON_BATCH = 4, - LOGON32_LOGON_SERVICE = 5, - LOGON32_LOGON_UNLOCK = 7, - LOGON32_LOGON_NETWORK_CLEARTEXT = 8, - LOGON32_LOGON_NEW_CREDENTIALS = 9 - } - - // SECURITY_LOGON_TYPE - public enum SecurityLogonType - { - Interactive = 2, // Interactively logged on (locally or remotely) - Network, // Accessing system via network - Batch, // Started via a batch queue - Service, // Service started by service controller - Proxy, // Proxy logon - Unlock, // Unlock workstation - NetworkCleartext, // Network logon with cleartext credentials - NewCredentials, // Clone caller, new default credentials - RemoteInteractive, // Remote, yet interactive. Terminal server - CachedInteractive, // Try cached credentials without hitting the net. - CachedRemoteInteractive, // Same as RemoteInteractive, this is used internally for auditing purpose - CachedUnlock // Cached Unlock workstation - } - - [StructLayout(LayoutKind.Sequential)] - public struct LSA_UNICODE_STRING - { - public UInt16 Length; - public UInt16 MaximumLength; - public IntPtr Buffer; - } - - [StructLayout(LayoutKind.Sequential)] - public struct TOKEN_SOURCE - { - public TOKEN_SOURCE(string name) - { - SourceName = new byte[8]; - System.Text.Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0); - if (!ADVAPI32.AllocateLocallyUniqueId(out SourceIdentifier)) - throw new System.ComponentModel.Win32Exception(); - } - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] SourceName; - public IntPtr SourceIdentifier; - } - [StructLayout(LayoutKind.Sequential)] - public struct KERB_INTERACTIVE_LOGON - { - public KERB_LOGON_SUBMIT_TYPE MessageType; - public string LogonDomainName; - public string UserName; - public string Password; - } - public enum KERB_LOGON_SUBMIT_TYPE - { - KerbInteractiveLogon = 2, - KerbSmartCardLogon = 6, - KerbWorkstationUnlockLogon = 7, - KerbSmartCardUnlockLogon = 8, - KerbProxyLogon = 9, - KerbTicketLogon = 10, - KerbTicketUnlockLogon = 11, - KerbS4ULogon = 12, - KerbCertificateLogon = 13, - KerbCertificateS4ULogon = 14, - KerbCertificateUnlockLogon = 15 - } - public enum TOKEN_INFORMATION_CLASS - { - /// -     /// The buffer receives a TOKEN_USER structure that contains the user account of the token. -     /// - TokenUser = 1, - - /// -     /// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token. -     /// - TokenGroups, - - /// -     /// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token. -     /// - TokenPrivileges, - - /// -     /// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects. -     /// - TokenOwner, - - /// -     /// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects. -     /// - TokenPrimaryGroup, - - /// -     /// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects. -     /// - TokenDefaultDacl, - - /// -     /// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information. -     /// - TokenSource, - - /// -     /// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token. -     /// - TokenType, - - /// -     /// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails. -     /// - TokenImpersonationLevel, - - /// -     /// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics. -     /// - TokenStatistics, - - /// -     /// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token. -     /// - TokenRestrictedSids, - - /// -     /// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token. -     /// - TokenSessionId, - - /// -     /// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token. -     /// - TokenGroupsAndPrivileges, - - /// -     /// Reserved. -     /// - TokenSessionReference, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag. -     /// - TokenSandBoxInert, - - /// -     /// Reserved. -     /// - TokenAuditPolicy, - - /// -     /// The buffer receives a TOKEN_ORIGIN value. -     /// - TokenOrigin, - - /// -     /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token. -     /// - TokenElevationType, - - /// -     /// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token. -     /// - TokenLinkedToken, - - /// -     /// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated. -     /// - TokenElevation, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token has ever been filtered. -     /// - TokenHasRestrictions, - - /// -     /// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token. -     /// - TokenAccessInformation, - - /// -     /// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token. -     /// - TokenVirtualizationAllowed, - - /// -     /// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token. -     /// - TokenVirtualizationEnabled, - - /// -     /// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level. -     /// - TokenIntegrityLevel, - - /// -     /// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set. -     /// - TokenUIAccess, - - /// -     /// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy. -     /// - TokenMandatoryPolicy, - - /// -     /// The buffer receives the token's logon security identifier (SID). -     /// - TokenLogonSid, - - /// -     /// The maximum value for this enumeration -     /// - MaxTokenInfoClass - } - [StructLayout(LayoutKind.Sequential)] - public struct QUOTA_LIMITS - { - readonly UInt32 PagedPoolLimit; - readonly UInt32 NonPagedPoolLimit; - readonly UInt32 MinimumWorkingSetSize; - readonly UInt32 MaximumWorkingSetSize; - readonly UInt32 PagefileLimit; - readonly Int64 TimeLimit; - } - - [StructLayout(LayoutKind.Sequential)] - public struct LSA_STRING - { - public UInt16 Length; - public UInt16 MaximumLength; - public /*PCHAR*/ IntPtr Buffer; - } - - - [DllImport("secur32.dll", SetLastError = true)] - public static extern WinStatusCodes LsaLogonUser( - [In] IntPtr LsaHandle, - [In] ref LSA_STRING OriginName, - [In] SecurityLogonType LogonType, - [In] UInt32 AuthenticationPackage, - [In] IntPtr AuthenticationInformation, - [In] UInt32 AuthenticationInformationLength, - [In] /*PTOKEN_GROUPS*/ IntPtr LocalGroups, - [In] ref TOKEN_SOURCE SourceContext, - [Out] /*PVOID*/ out IntPtr ProfileBuffer, - [Out] out UInt32 ProfileBufferLength, - [Out] out Int64 LogonId, - [Out] out IntPtr Token, - [Out] out QUOTA_LIMITS Quotas, - [Out] out WinStatusCodes SubStatus - ); - - [DllImport("secur32.dll", SetLastError = true)] - public static extern WinStatusCodes LsaRegisterLogonProcess( - IntPtr LogonProcessName, - out IntPtr LsaHandle, - out ulong SecurityMode - ); - - [DllImport("secur32.dll", SetLastError = false)] - public static extern WinStatusCodes LsaLookupAuthenticationPackage([In] IntPtr LsaHandle, [In] ref LSA_STRING PackageName, [Out] out UInt32 AuthenticationPackage); - - [DllImport("secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] - [ResourceExposure(ResourceScope.None)] - internal static extern int LsaConnectUntrusted( - [In, Out] ref SafeLsaLogonProcessHandle LsaHandle); - - [DllImport("secur32.dll", SetLastError = false)] - public static extern WinStatusCodes LsaConnectUntrusted([Out] out IntPtr LsaHandle); - - [System.Security.SecurityCritical] // auto-generated - internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid - { - private SafeLsaLogonProcessHandle() : base(true) { } - - // 0 is an Invalid Handle - internal SafeLsaLogonProcessHandle(IntPtr handle) : base(true) - { - SetHandle(handle); - } - - internal static SafeLsaLogonProcessHandle InvalidHandle - { - get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); } - } - - [System.Security.SecurityCritical] - protected override bool ReleaseHandle() - { - // LsaDeregisterLogonProcess returns an NTSTATUS - return LsaDeregisterLogonProcess(handle) >= 0; - } - } - - [DllImport("secur32.dll", SetLastError = true)] - [ResourceExposure(ResourceScope.None)] - internal static extern int LsaDeregisterLogonProcess(IntPtr handle); - - - public static void CreateNewSession() - { - var kli = new SECUR32.KERB_INTERACTIVE_LOGON() - { - MessageType = SECUR32.KERB_LOGON_SUBMIT_TYPE.KerbInteractiveLogon, - UserName = "", - Password = "" - }; - IntPtr kerbLogInfo; - SECUR32.LSA_STRING logonProc = new() - { - Buffer = Marshal.StringToHGlobalAuto("InstaLogon"), - Length = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")), - MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")) - }; - SECUR32.LSA_STRING originName = new() - { - Buffer = Marshal.StringToHGlobalAuto("InstaLogon"), - Length = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")), - MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("InstaLogon")) - }; - SECUR32.LSA_STRING authPackage = new() - { - Buffer = Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A"), - Length = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A")), - MaximumLength = (ushort)Marshal.SizeOf(Marshal.StringToHGlobalAuto("MICROSOFT_KERBEROS_NAME_A")) - }; - IntPtr hLogonProc = Marshal.AllocHGlobal(Marshal.SizeOf(logonProc)); - Marshal.StructureToPtr(logonProc, hLogonProc, false); - ADVAPI32.AllocateLocallyUniqueId(out IntPtr pluid); - LsaConnectUntrusted(out IntPtr lsaHan); - //SECUR32.LsaRegisterLogonProcess(hLogonProc, out lsaHan, out secMode); - SECUR32.LsaLookupAuthenticationPackage(lsaHan, ref authPackage, out uint authPackID); - - kerbLogInfo = Marshal.AllocHGlobal(Marshal.SizeOf(kli)); - Marshal.StructureToPtr(kli, kerbLogInfo, false); - - var ts = new SECUR32.TOKEN_SOURCE("Insta"); - SECUR32.LsaLogonUser( - lsaHan, - ref originName, - SECUR32.SecurityLogonType.Interactive, - authPackID, - kerbLogInfo, - (uint)Marshal.SizeOf(kerbLogInfo), - IntPtr.Zero, - ref ts, - out IntPtr profBuf, - out uint profBufLen, - out long logonID, - out IntPtr logonToken, - out QUOTA_LIMITS quotas, - out WinStatusCodes subStatus); - } -} \ No newline at end of file diff --git a/Shared/Win32/Shlwapi.cs b/Shared/Win32/Shlwapi.cs deleted file mode 100644 index 716c8e0c5..000000000 --- a/Shared/Win32/Shlwapi.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Runtime.InteropServices; - -namespace Remotely.Shared.Win32 -{ - // https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-isos - public class Shlwapi - { - [DllImport("shlwapi.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool IsOS(OsType osType); - } - - public enum OsType - { - OS_WINDOWS = 0, - OS_NT = 1, - OS_WIN95ORGREATER = 2, - OS_NT4ORGREATER = 3, - OS_WIN98ORGREATER = 5, - OS_WIN98_GOLD = 6, - OS_WIN2000ORGREATER = 7, - OS_WIN2000PRO = 8, - OS_WIN2000SERVER = 9, - OS_WIN2000ADVSERVER = 10, - OS_WIN2000DATACENTER = 11, - OS_WIN2000TERMINAL = 12, - OS_EMBEDDED = 13, - OS_TERMINALCLIENT = 14, - OS_TERMINALREMOTEADMIN = 15, - OS_WIN95_GOLD = 16, - OS_MEORGREATER = 17, - OS_XPORGREATER = 18, - OS_HOME = 19, - OS_PROFESSIONAL = 20, - OS_DATACENTER = 21, - OS_ADVSERVER = 22, - OS_SERVER = 23, - OS_TERMINALSERVER = 24, - OS_PERSONALTERMINALSERVER = 25, - OS_FASTUSERSWITCHING = 26, - OS_WELCOMELOGONUI = 27, - OS_DOMAINMEMBER = 28, - OS_ANYSERVER = 29, - OS_WOW6432 = 30, - OS_WEBSERVER = 31, - OS_SMALLBUSINESSSERVER = 32, - OS_TABLETPC = 33, - OS_SERVERADMINUI = 34, - OS_MEDIACENTER = 35, - OS_APPLIANCE = 36, - } -} diff --git a/Shared/Win32/User32.cs b/Shared/Win32/User32.cs deleted file mode 100644 index 44ee2fe08..000000000 --- a/Shared/Win32/User32.cs +++ /dev/null @@ -1,1319 +0,0 @@ -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; - -namespace Remotely.Shared.Win32 -{ - public static class User32 - { - #region Constants - public const Int32 CURSOR_SHOWING = 0x00000001; - public const uint MOUSEEVENTF_ABSOLUTE = 0x8000; - public const int MOUSEEVENTF_LEFTDOWN = 0x02; - public const int MOUSEEVENTF_LEFTUP = 0x04; - public const int MOUSEEVENTF_RIGHTDOWN = 0x08; - public const int MOUSEEVENTF_RIGHTUP = 0x10; - public const int MOUSEEVENTF_MOVE = 0x0001; - public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; - public const uint KEYEVENTF_KEYUP = 0x0002; - - public const int SPIF_SENDWININICHANGE = 0x02; - public const int SPI_SETDESKWALLPAPER = 20; - public const int SPIF_UPDATEINIFILE = 1; - public const int SPIF_SENDCHANGE = 2; - - public static readonly int SPI_GETDESKWALLPAPER = 0x73; - public static readonly int MAX_PATH = 260; - #endregion - - #region Enums - [Flags] - public enum MouseEventFlags : uint - { - LEFTDOWN = 0x00000002, - LEFTUP = 0x00000004, - MIDDLEDOWN = 0x00000020, - MIDDLEUP = 0x00000040, - MOVE = 0x00000001, - ABSOLUTE = 0x00008000, - RIGHTDOWN = 0x00000008, - RIGHTUP = 0x00000010, - WHEEL = 0x00000800, - XDOWN = 0x00000080, - XUP = 0x00000100 - } - [Flags] - public enum MOUSEEVENTF : uint - { - ABSOLUTE = 0x8000, - HWHEEL = 0x01000, - MOVE = 0x0001, - MOVE_NOCOALESCE = 0x2000, - LEFTDOWN = 0x0002, - LEFTUP = 0x0004, - RIGHTDOWN = 0x0008, - RIGHTUP = 0x0010, - MIDDLEDOWN = 0x0020, - MIDDLEUP = 0x0040, - VIRTUALDESK = 0x4000, - WHEEL = 0x0800, - XDOWN = 0x0080, - XUP = 0x0100 - } - public enum MonitorState - { - MonitorStateOn = -1, - MonitorStateOff = 2, - MonitorStateStandBy = 1 - } - [Flags] - public enum KEYEVENTF : uint - { - EXTENDEDKEY = 0x0001, - KEYUP = 0x0002, - SCANCODE = 0x0008, - UNICODE = 0x0004 - } - - public enum VirtualKey : short - { - /// -         ///Left mouse button -         /// - LBUTTON = 0x01, - /// -         ///Right mouse button -         /// - RBUTTON = 0x02, - /// -         ///Control-break processing -         /// - CANCEL = 0x03, - /// -         ///Middle mouse button (three-button mouse) -         /// - MBUTTON = 0x04, - /// -         ///Windows 2000/XP: X1 mouse button -         /// - XBUTTON1 = 0x05, - /// -         ///Windows 2000/XP: X2 mouse button -         /// - XBUTTON2 = 0x06, - /// -         ///BACKSPACE key -         /// - BACK = 0x08, - /// -         ///TAB key -         /// - TAB = 0x09, - /// -         ///CLEAR key -         /// - CLEAR = 0x0C, - /// -         ///ENTER key -         /// - RETURN = 0x0D, - /// -         ///SHIFT key -         /// - SHIFT = 0x10, - /// -         ///CTRL key -         /// - CONTROL = 0x11, - /// -         ///ALT key -         /// - MENU = 0x12, - /// -         ///PAUSE key -         /// - PAUSE = 0x13, - /// -         ///CAPS LOCK key -         /// - CAPITAL = 0x14, - /// -         ///Input Method Editor (IME) Kana mode -         /// - KANA = 0x15, - /// -         ///IME Hangul mode -         /// - HANGUL = 0x15, - /// -         ///IME Junja mode -         /// - JUNJA = 0x17, - /// -         ///IME final mode -         /// - FINAL = 0x18, - /// -         ///IME Hanja mode -         /// - HANJA = 0x19, - /// -         ///IME Kanji mode -         /// - KANJI = 0x19, - /// -         ///ESC key -         /// - ESCAPE = 0x1B, - /// -         ///IME convert -         /// - CONVERT = 0x1C, - /// -         ///IME nonconvert -         /// - NONCONVERT = 0x1D, - /// -         ///IME accept -         /// - ACCEPT = 0x1E, - /// -         ///IME mode change request -         /// - MODECHANGE = 0x1F, - /// -         ///SPACEBAR -         /// - SPACE = 0x20, - /// -         ///PAGE UP key -         /// - PRIOR = 0x21, - /// -         ///PAGE DOWN key -         /// - NEXT = 0x22, - /// -         ///END key -         /// - END = 0x23, - /// -         ///HOME key -         /// - HOME = 0x24, - /// -         ///LEFT ARROW key -         /// - LEFT = 0x25, - /// -         ///UP ARROW key -         /// - UP = 0x26, - /// -         ///RIGHT ARROW key -         /// - RIGHT = 0x27, - /// -         ///DOWN ARROW key -         /// - DOWN = 0x28, - /// -         ///SELECT key -         /// - SELECT = 0x29, - /// -         ///PRINT key -         /// - PRINT = 0x2A, - /// -         ///EXECUTE key -         /// - EXECUTE = 0x2B, - /// -         ///PRINT SCREEN key -         /// - SNAPSHOT = 0x2C, - /// -         ///INS key -         /// - INSERT = 0x2D, - /// -         ///DEL key -         /// - DELETE = 0x2E, - /// -         ///HELP key -         /// - HELP = 0x2F, - /// -         ///0 key -         /// - KEY_0 = 0x30, - /// -         ///1 key -         /// - KEY_1 = 0x31, - /// -         ///2 key -         /// - KEY_2 = 0x32, - /// -         ///3 key -         /// - KEY_3 = 0x33, - /// -         ///4 key -         /// - KEY_4 = 0x34, - /// -         ///5 key -         /// - KEY_5 = 0x35, - /// -         ///6 key -         /// - KEY_6 = 0x36, - /// -         ///7 key -         /// - KEY_7 = 0x37, - /// -         ///8 key -         /// - KEY_8 = 0x38, - /// -         ///9 key -         /// - KEY_9 = 0x39, - /// -         ///A key -         /// - KEY_A = 0x41, - /// -         ///B key -         /// - KEY_B = 0x42, - /// -         ///C key -         /// - KEY_C = 0x43, - /// -         ///D key -         /// - KEY_D = 0x44, - /// -         ///E key -         /// - KEY_E = 0x45, - /// -         ///F key -         /// - KEY_F = 0x46, - /// -         ///G key -         /// - KEY_G = 0x47, - /// -         ///H key -         /// - KEY_H = 0x48, - /// -         ///I key -         /// - KEY_I = 0x49, - /// -         ///J key -         /// - KEY_J = 0x4A, - /// -         ///K key -         /// - KEY_K = 0x4B, - /// -         ///L key -         /// - KEY_L = 0x4C, - /// -         ///M key -         /// - KEY_M = 0x4D, - /// -         ///N key -         /// - KEY_N = 0x4E, - /// -         ///O key -         /// - KEY_O = 0x4F, - /// -         ///P key -         /// - KEY_P = 0x50, - /// -         ///Q key -         /// - KEY_Q = 0x51, - /// -         ///R key -         /// - KEY_R = 0x52, - /// -         ///S key -         /// - KEY_S = 0x53, - /// -         ///T key -         /// - KEY_T = 0x54, - /// -         ///U key -         /// - KEY_U = 0x55, - /// -         ///V key -         /// - KEY_V = 0x56, - /// -         ///W key -         /// - KEY_W = 0x57, - /// -         ///X key -         /// - KEY_X = 0x58, - /// -         ///Y key -         /// - KEY_Y = 0x59, - /// -         ///Z key -         /// - KEY_Z = 0x5A, - /// -         ///Left Windows key (Microsoft Natural keyboard) -         /// - LWIN = 0x5B, - /// -         ///Right Windows key (Natural keyboard) -         /// - RWIN = 0x5C, - /// -         ///Applications key (Natural keyboard) -         /// - APPS = 0x5D, - /// -         ///Computer Sleep key -         /// - SLEEP = 0x5F, - /// -         ///Numeric keypad 0 key -         /// - NUMPAD0 = 0x60, - /// -         ///Numeric keypad 1 key -         /// - NUMPAD1 = 0x61, - /// -         ///Numeric keypad 2 key -         /// - NUMPAD2 = 0x62, - /// -         ///Numeric keypad 3 key -         /// - NUMPAD3 = 0x63, - /// -         ///Numeric keypad 4 key -         /// - NUMPAD4 = 0x64, - /// -         ///Numeric keypad 5 key -         /// - NUMPAD5 = 0x65, - /// -         ///Numeric keypad 6 key -         /// - NUMPAD6 = 0x66, - /// -         ///Numeric keypad 7 key -         /// - NUMPAD7 = 0x67, - /// -         ///Numeric keypad 8 key -         /// - NUMPAD8 = 0x68, - /// -         ///Numeric keypad 9 key -         /// - NUMPAD9 = 0x69, - /// -         ///Multiply key -         /// - MULTIPLY = 0x6A, - /// -         ///Add key -         /// - ADD = 0x6B, - /// -         ///Separator key -         /// - SEPARATOR = 0x6C, - /// -         ///Subtract key -         /// - SUBTRACT = 0x6D, - /// -         ///Decimal key -         /// - DECIMAL = 0x6E, - /// -         ///Divide key -         /// - DIVIDE = 0x6F, - /// -         ///F1 key -         /// - F1 = 0x70, - /// -         ///F2 key -         /// - F2 = 0x71, - /// -         ///F3 key -         /// - F3 = 0x72, - /// -         ///F4 key -         /// - F4 = 0x73, - /// -         ///F5 key -         /// - F5 = 0x74, - /// -         ///F6 key -         /// - F6 = 0x75, - /// -         ///F7 key -         /// - F7 = 0x76, - /// -         ///F8 key -         /// - F8 = 0x77, - /// -         ///F9 key -         /// - F9 = 0x78, - /// -         ///F10 key -         /// - F10 = 0x79, - /// -         ///F11 key -         /// - F11 = 0x7A, - /// -         ///F12 key -         /// - F12 = 0x7B, - /// -         ///F13 key -         /// - F13 = 0x7C, - /// -         ///F14 key -         /// - F14 = 0x7D, - /// -         ///F15 key -         /// - F15 = 0x7E, - /// -         ///F16 key -         /// - F16 = 0x7F, - /// -         ///F17 key   -         /// - F17 = 0x80, - /// -         ///F18 key   -         /// - F18 = 0x81, - /// -         ///F19 key   -         /// - F19 = 0x82, - /// -         ///F20 key   -         /// - F20 = 0x83, - /// -         ///F21 key   -         /// - F21 = 0x84, - /// -         ///F22 key, (PPC only) Key used to lock device. -         /// - F22 = 0x85, - /// -         ///F23 key   -         /// - F23 = 0x86, - /// -         ///F24 key   -         /// - F24 = 0x87, - /// -         ///NUM LOCK key -         /// - NUMLOCK = 0x90, - /// -         ///SCROLL LOCK key -         /// - SCROLL = 0x91, - /// -         ///Left SHIFT key -         /// - LSHIFT = 0xA0, - /// -         ///Right SHIFT key -         /// - RSHIFT = 0xA1, - /// -         ///Left CONTROL key -         /// - LCONTROL = 0xA2, - /// -         ///Right CONTROL key -         /// - RCONTROL = 0xA3, - /// -         ///Left MENU key -         /// - LMENU = 0xA4, - /// -         ///Right MENU key -         /// - RMENU = 0xA5, - /// -         ///Windows 2000/XP: Browser Back key -         /// - BROWSER_BACK = 0xA6, - /// -         ///Windows 2000/XP: Browser Forward key -         /// - BROWSER_FORWARD = 0xA7, - /// -         ///Windows 2000/XP: Browser Refresh key -         /// - BROWSER_REFRESH = 0xA8, - /// -         ///Windows 2000/XP: Browser Stop key -         /// - BROWSER_STOP = 0xA9, - /// -         ///Windows 2000/XP: Browser Search key -         /// - BROWSER_SEARCH = 0xAA, - /// -         ///Windows 2000/XP: Browser Favorites key -         /// - BROWSER_FAVORITES = 0xAB, - /// -         ///Windows 2000/XP: Browser Start and Home key -         /// - BROWSER_HOME = 0xAC, - /// -         ///Windows 2000/XP: Volume Mute key -         /// - VOLUME_MUTE = 0xAD, - /// -         ///Windows 2000/XP: Volume Down key -         /// - VOLUME_DOWN = 0xAE, - /// -         ///Windows 2000/XP: Volume Up key -         /// - VOLUME_UP = 0xAF, - /// -         ///Windows 2000/XP: Next Track key -         /// - MEDIA_NEXT_TRACK = 0xB0, - /// -         ///Windows 2000/XP: Previous Track key -         /// - MEDIA_PREV_TRACK = 0xB1, - /// -         ///Windows 2000/XP: Stop Media key -         /// - MEDIA_STOP = 0xB2, - /// -         ///Windows 2000/XP: Play/Pause Media key -         /// - MEDIA_PLAY_PAUSE = 0xB3, - /// -         ///Windows 2000/XP: Start Mail key -         /// - LAUNCH_MAIL = 0xB4, - /// -         ///Windows 2000/XP: Select Media key -         /// - LAUNCH_MEDIA_SELECT = 0xB5, - /// -         ///Windows 2000/XP: Start Application 1 key -         /// - LAUNCH_APP1 = 0xB6, - /// -         ///Windows 2000/XP: Start Application 2 key -         /// - LAUNCH_APP2 = 0xB7, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_1 = 0xBA, - /// -         ///Windows 2000/XP: For any country/region, the '+' key -         /// - OEM_PLUS = 0xBB, - /// -         ///Windows 2000/XP: For any country/region, the ',' key -         /// - OEM_COMMA = 0xBC, - /// -         ///Windows 2000/XP: For any country/region, the '-' key -         /// - OEM_MINUS = 0xBD, - /// -         ///Windows 2000/XP: For any country/region, the '.' key -         /// - OEM_PERIOD = 0xBE, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_2 = 0xBF, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_3 = 0xC0, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_4 = 0xDB, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_5 = 0xDC, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_6 = 0xDD, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_7 = 0xDE, - /// -         ///Used for miscellaneous characters; it can vary by keyboard. -         /// - OEM_8 = 0xDF, - /// -         ///Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard -         /// - OEM_102 = 0xE2, - /// -         ///Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key -         /// - PROCESSKEY = 0xE5, - /// -         ///Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. -         ///The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, -         ///see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP -         /// - PACKET = 0xE7, - /// -         ///Attn key -         /// - ATTN = 0xF6, - /// -         ///CrSel key -         /// - CRSEL = 0xF7, - /// -         ///ExSel key -         /// - EXSEL = 0xF8, - /// -         ///Erase EOF key -         /// - EREOF = 0xF9, - /// -         ///Play key -         /// - PLAY = 0xFA, - /// -         ///Zoom key -         /// - ZOOM = 0xFB, - /// -         ///Reserved -         /// - NONAME = 0xFC, - /// -         ///PA1 key -         /// - PA1 = 0xFD, - /// -         ///Clear key -         /// - OEM_CLEAR = 0xFE - } - public enum ScanCodeShort : short - { - LBUTTON = 0, - RBUTTON = 0, - CANCEL = 70, - MBUTTON = 0, - XBUTTON1 = 0, - XBUTTON2 = 0, - BACK = 14, - TAB = 15, - CLEAR = 76, - RETURN = 28, - SHIFT = 42, - CONTROL = 29, - MENU = 56, - PAUSE = 0, - CAPITAL = 58, - KANA = 0, - HANGUL = 0, - JUNJA = 0, - FINAL = 0, - HANJA = 0, - KANJI = 0, - ESCAPE = 1, - CONVERT = 0, - NONCONVERT = 0, - ACCEPT = 0, - MODECHANGE = 0, - SPACE = 57, - PRIOR = 73, - NEXT = 81, - END = 79, - HOME = 71, - LEFT = 75, - UP = 72, - RIGHT = 77, - DOWN = 80, - SELECT = 0, - PRINT = 0, - EXECUTE = 0, - SNAPSHOT = 84, - INSERT = 82, - DELETE = 83, - HELP = 99, - KEY_0 = 11, - KEY_1 = 2, - KEY_2 = 3, - KEY_3 = 4, - KEY_4 = 5, - KEY_5 = 6, - KEY_6 = 7, - KEY_7 = 8, - KEY_8 = 9, - KEY_9 = 10, - KEY_A = 30, - KEY_B = 48, - KEY_C = 46, - KEY_D = 32, - KEY_E = 18, - KEY_F = 33, - KEY_G = 34, - KEY_H = 35, - KEY_I = 23, - KEY_J = 36, - KEY_K = 37, - KEY_L = 38, - KEY_M = 50, - KEY_N = 49, - KEY_O = 24, - KEY_P = 25, - KEY_Q = 16, - KEY_R = 19, - KEY_S = 31, - KEY_T = 20, - KEY_U = 22, - KEY_V = 47, - KEY_W = 17, - KEY_X = 45, - KEY_Y = 21, - KEY_Z = 44, - LWIN = 91, - RWIN = 92, - APPS = 93, - SLEEP = 95, - NUMPAD0 = 82, - NUMPAD1 = 79, - NUMPAD2 = 80, - NUMPAD3 = 81, - NUMPAD4 = 75, - NUMPAD5 = 76, - NUMPAD6 = 77, - NUMPAD7 = 71, - NUMPAD8 = 72, - NUMPAD9 = 73, - MULTIPLY = 55, - ADD = 78, - SEPARATOR = 0, - SUBTRACT = 74, - DECIMAL = 83, - DIVIDE = 53, - F1 = 59, - F2 = 60, - F3 = 61, - F4 = 62, - F5 = 63, - F6 = 64, - F7 = 65, - F8 = 66, - F9 = 67, - F10 = 68, - F11 = 87, - F12 = 88, - F13 = 100, - F14 = 101, - F15 = 102, - F16 = 103, - F17 = 104, - F18 = 105, - F19 = 106, - F20 = 107, - F21 = 108, - F22 = 109, - F23 = 110, - F24 = 118, - NUMLOCK = 69, - SCROLL = 70, - LSHIFT = 42, - RSHIFT = 54, - LCONTROL = 29, - RCONTROL = 29, - LMENU = 56, - RMENU = 56, - BROWSER_BACK = 106, - BROWSER_FORWARD = 105, - BROWSER_REFRESH = 103, - BROWSER_STOP = 104, - BROWSER_SEARCH = 101, - BROWSER_FAVORITES = 102, - BROWSER_HOME = 50, - VOLUME_MUTE = 32, - VOLUME_DOWN = 46, - VOLUME_UP = 48, - MEDIA_NEXT_TRACK = 25, - MEDIA_PREV_TRACK = 16, - MEDIA_STOP = 36, - MEDIA_PLAY_PAUSE = 34, - LAUNCH_MAIL = 108, - LAUNCH_MEDIA_SELECT = 109, - LAUNCH_APP1 = 107, - LAUNCH_APP2 = 33, - OEM_1 = 39, - OEM_PLUS = 13, - OEM_COMMA = 51, - OEM_MINUS = 12, - OEM_PERIOD = 52, - OEM_2 = 53, - OEM_3 = 41, - OEM_4 = 26, - OEM_5 = 43, - OEM_6 = 27, - OEM_7 = 40, - OEM_8 = 0, - OEM_102 = 86, - PROCESSKEY = 0, - PACKET = 0, - ATTN = 0, - CRSEL = 0, - EXSEL = 0, - EREOF = 93, - PLAY = 0, - ZOOM = 98, - NONAME = 0, - PA1 = 0, - OEM_CLEAR = 0, - } - [Flags] - public enum ACCESS_MASK : uint - { - DELETE = 0x00010000, - READ_CONTROL = 0x00020000, - WRITE_DAC = 0x00040000, - WRITE_OWNER = 0x00080000, - SYNCHRONIZE = 0x00100000, - - STANDARD_RIGHTS_REQUIRED = 0x000F0000, - - STANDARD_RIGHTS_READ = 0x00020000, - STANDARD_RIGHTS_WRITE = 0x00020000, - STANDARD_RIGHTS_EXECUTE = 0x00020000, - - STANDARD_RIGHTS_ALL = 0x001F0000, - - SPECIFIC_RIGHTS_ALL = 0x0000FFFF, - - ACCESS_SYSTEM_SECURITY = 0x01000000, - - MAXIMUM_ALLOWED = 0x02000000, - - GENERIC_READ = 0x80000000, - GENERIC_WRITE = 0x40000000, - GENERIC_EXECUTE = 0x20000000, - GENERIC_ALL = 0x10000000, - - DESKTOP_READOBJECTS = 0x00000001, - DESKTOP_CREATEWINDOW = 0x00000002, - DESKTOP_CREATEMENU = 0x00000004, - DESKTOP_HOOKCONTROL = 0x00000008, - DESKTOP_JOURNALRECORD = 0x00000010, - DESKTOP_JOURNALPLAYBACK = 0x00000020, - DESKTOP_ENUMERATE = 0x00000040, - DESKTOP_WRITEOBJECTS = 0x00000080, - DESKTOP_SWITCHDESKTOP = 0x00000100, - - WINSTA_ENUMDESKTOPS = 0x00000001, - WINSTA_READATTRIBUTES = 0x00000002, - WINSTA_ACCESSCLIPBOARD = 0x00000004, - WINSTA_CREATEDESKTOP = 0x00000008, - WINSTA_WRITEATTRIBUTES = 0x00000010, - WINSTA_ACCESSGLOBALATOMS = 0x00000020, - WINSTA_EXITWINDOWS = 0x00000040, - WINSTA_ENUMERATE = 0x00000100, - WINSTA_READSCREEN = 0x00000200, - - WINSTA_ALL_ACCESS = 0x0000037F - } - public enum InputType : uint - { - MOUSE = 0, - KEYBOARD = 1, - HARDWARE = 2 - } - public enum MessageBoxType : long - { - MB_ABORTRETRYIGNORE = 0x00000002L, - MB_CANCELTRYCONTINUE = 0x00000006L, - MB_HELP = 0x00004000L, - MB_OK = 0x00000000L, - MB_OKCANCEL = 0x00000001L, - MB_RETRYCANCEL = 0x00000005L, - MB_YESNO = 0x00000004L, - MB_YESNOCANCEL = 0x00000003L, - MB_ICONEXCLAMATION = 0x00000030L, - MB_ICONWARNING = 0x00000030L, - MB_ICONINFORMATION = 0x00000040L, - MB_ICONASTERISK = 0x00000040L, - MB_ICONQUESTION = 0x00000020L, - MB_ICONSTOP = 0x00000010L, - MB_ICONERROR = 0x00000010L, - MB_ICONHAND = 0x00000010L, - MB_DEFBUTTON1 = 0x00000000L, - MB_DEFBUTTON2 = 0x00000100L, - MB_DEFBUTTON3 = 0x00000200L, - MB_DEFBUTTON4 = 0x00000300L, - MB_APPLMODAL = 0x00000000L, - MB_SYSTEMMODAL = 0x00001000L, - MB_TASKMODAL = 0x00002000L, - MB_DEFAULT_DESKTOP_ONLY = 0x00020000L, - MB_RIGHT = 0x00080000L, - MB_RTLREADING = 0x00100000L, - MB_SETFOREGROUND = 0x00010000L, - MB_TOPMOST = 0x00040000L, - MB_SERVICE_NOTIFICATION = 0x00200000L - } - - public enum MessageBoxResult : int - { - IDABORT = 3, - IDCANCEL = 2, - IDCONTINUE = 11, - IDIGNORE = 5, - IDNO = 7, - IDOK = 1, - IDRETRY = 4, - IDTRYAGAIN = 10, - IDYES = 6, - } - public enum VkMapType : uint - { - MAPVK_VK_TO_VSC = 0, - MAPVK_VSC_TO_VK = 1, - MAPVK_VK_TO_CHAR = 2, - MAPVK_VSC_TO_VK_EX = 3, - MAPVK_VK_TO_VSC_EX = 4 - } - - #endregion - - #region Structs - [StructLayout(LayoutKind.Sequential)] - public struct ICONINFO - { - public bool fIcon; - public Int32 xHotspot; - public Int32 yHotspot; - public IntPtr hbmMask; - public IntPtr hbmColor; - } - - [StructLayout(LayoutKind.Sequential)] - public struct POINT - { - public int x; - public int y; - } - - - [StructLayout(LayoutKind.Sequential)] - public struct CursorInfo - { - public Int32 cbSize; - public Int32 flags; - public IntPtr hCursor; - public POINT ptScreenPos; - } - [StructLayout(LayoutKind.Sequential)] - public struct INPUT - { - public InputType type; - public InputUnion U; - public static int Size - { - get { return Marshal.SizeOf(typeof(INPUT)); } - } - } - - [StructLayout(LayoutKind.Explicit)] - public struct InputUnion - { - [FieldOffset(0)] - public MOUSEINPUT mi; - [FieldOffset(0)] - public KEYBDINPUT ki; - [FieldOffset(0)] - public HARDWAREINPUT hi; - } - [StructLayout(LayoutKind.Sequential)] - public struct MOUSEINPUT - { - public int dx; - public int dy; - public int mouseData; - public MOUSEEVENTF dwFlags; - public uint time; - public UIntPtr dwExtraInfo; - } - [StructLayout(LayoutKind.Sequential)] - public struct KEYBDINPUT - { - public VirtualKey wVk; - public ScanCodeShort wScan; - public KEYEVENTF dwFlags; - public int time; - public UIntPtr dwExtraInfo; - } - [StructLayout(LayoutKind.Sequential)] - public struct HARDWAREINPUT - { - public int uMsg; - public short wParamL; - public short wParamH; - } - #endregion - - #region DLL Imports - [DllImport("user32.dll")] - public static extern bool GetCursorInfo(out CursorInfo pci); - [DllImport("user32.dll", SetLastError = false)] - public static extern IntPtr GetDesktopWindow(); - - [DllImport("user32.dll")] - public static extern IntPtr GetCursor(); - - [DllImport("user32.dll")] - public static extern IntPtr CopyIcon(IntPtr hIcon); - - [DllImport("user32.dll")] - public static extern bool DrawIcon(IntPtr hdc, int x, int y, IntPtr hIcon); - - [DllImport("user32.dll")] - public static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO piconinfo); - - [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] - public static extern void Mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, UIntPtr dwExtraInfo); - - [DllImport("user32.dll")] - public static extern void Keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool GetCursorPos(out System.Drawing.Point lpPoint); - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool SetCursorPos(int x, int y); - - [DllImport("user32.dll")] - public static extern IntPtr SetCursor(IntPtr hcursor); - - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, - int cxDesired, int cyDesired, uint fuLoad); - - [DllImport("user32.dll")] - public static extern IntPtr CreateCursor(IntPtr hInst, int xHotSpot, int yHotSpot, - int nWidth, int nHeight, byte[] pvANDPlane, byte[] pvXORPlane); - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool SwitchDesktop(IntPtr hDesktop); - - public delegate bool EnumDesktopsDelegate(string desktop, IntPtr lParam); - - [DllImport("user32.dll")] - public static extern bool EnumDesktopsA(IntPtr hwinsta, EnumDesktopsDelegate lpEnumFunc, IntPtr lParam); - - [DllImport("user32.dll", SetLastError = true)] - public static extern IntPtr OpenInputDesktop(uint dwFlags, bool fInherit, ACCESS_MASK dwDesiredAccess); - - public delegate bool EnumWindowStationsDelegate(string windowsStation, IntPtr lParam); - - [DllImport("user32.dll")] - public static extern bool EnumWindowStations(EnumWindowStationsDelegate lpEnumFunc, IntPtr lParam); - - [DllImport("user32.dll")] - public static extern IntPtr GetShellWindow(); - - public sealed class SafeWindowStationHandle : SafeHandleZeroOrMinusOneIsInvalid - { - public SafeWindowStationHandle() - : base(true) - { - } - - protected override bool ReleaseHandle() - { - return CloseWindowStation(handle); - - } - } - - [return: MarshalAs(UnmanagedType.Bool)] - [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern bool CloseWindowStation(IntPtr hWinsta); - - [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern SafeWindowStationHandle OpenWindowStation([MarshalAs(UnmanagedType.LPTStr)] string lpszWinSta, [MarshalAs(UnmanagedType.Bool)] bool fInherit, ACCESS_MASK dwDesiredAccess); - - [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern IntPtr OpenWindowStationW([MarshalAs(UnmanagedType.LPTStr)] string lpszWinSta, [MarshalAs(UnmanagedType.Bool)] bool fInherit, ACCESS_MASK dwDesiredAccess); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool SetProcessWindowStation(IntPtr hWinSta); - - [DllImport("user32.dll")] - public static extern IntPtr GetWindowDC(IntPtr hWnd); - - public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); - - [DllImport("User32.dll")] - public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); - - [DllImport("User32.dll")] - public static extern IntPtr GetProcessWindowStation(); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool SetThreadDesktop(IntPtr hDesktop); - - [DllImport("user32.dll")] - public static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, ACCESS_MASK dwDesiredAccess); - [DllImport("user32.dll", SetLastError = true)] - public static extern bool CloseDesktop(IntPtr hDesktop); - - public delegate bool EnumDesktopWindowsDelegate(IntPtr hWnd, int lParam); - - [DllImport("user32.dll")] - public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsDelegate lpfn, IntPtr lParam); - - [DllImport("user32.dll")] - public static extern IntPtr GetDC(IntPtr hWnd); - - [DllImport("user32.dll", SetLastError = true)] - public static extern IntPtr SetActiveWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - public static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs, int cbSize); - [DllImport("user32.dll", SetLastError = false)] - public static extern UIntPtr GetMessageExtraInfo(); - [DllImport("sas.dll")] - public static extern void SendSAS(bool AsUser); - [DllImport("user32.dll")] - public static extern bool OpenClipboard(IntPtr hWnd); - [DllImport("user32.dll")] - public static extern bool EmptyClipboard(); - [DllImport("user32.dll")] - public static extern bool CloseClipboard(); - [DllImport("user32.dll")] - public static extern IntPtr SetClipboardData(int Format, IntPtr hMem); - - [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)] - public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - /* - * SystemParametersInfo( - * SPI_SETDESKWALLPAPER, 0, "filename.bmp", - * SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); - */ - - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern int SystemParametersInfo( - int uAction, int uParam, string lpvParam, int fuWinIni); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool LockWorkStation(); - - [DllImport("user32.dll")] - public static extern short VkKeyScan(char ch); - - [DllImport("user32.dll")] - public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); - - [DllImport("user32.dll", EntryPoint = "BlockInput")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt); - - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern int MessageBox(IntPtr hWnd, string text, string caption, long type); - - [DllImport("USER32.dll")] - public static extern short GetKeyState(VirtualKey nVirtKey); - - [DllImport("user32.dll")] - public static extern uint MapVirtualKeyEx(uint uCode, VkMapType uMapType, IntPtr dwhkl); - - [DllImport("user32.dll")] - public static extern IntPtr GetKeyboardLayout(uint threadId = 0); - - #endregion - } -} diff --git a/Shared/Win32/WTSAPI32.cs b/Shared/Win32/WTSAPI32.cs deleted file mode 100644 index 0ee903687..000000000 --- a/Shared/Win32/WTSAPI32.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace Remotely.Shared.Win32 -{ - public static class WTSAPI32 - { - public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; - - public enum WTS_CONNECTSTATE_CLASS - { - WTSActive, - WTSConnected, - WTSConnectQuery, - WTSShadow, - WTSDisconnected, - WTSIdle, - WTSListen, - WTSReset, - WTSDown, - WTSInit - } - - public enum WTS_INFO_CLASS - { - WTSInitialProgram, - WTSApplicationName, - WTSWorkingDirectory, - WTSOEMId, - WTSSessionId, - WTSUserName, - WTSWinStationName, - WTSDomainName, - WTSConnectState, - WTSClientBuildNumber, - WTSClientName, - WTSClientDirectory, - WTSClientProductId, - WTSClientHardwareId, - WTSClientAddress, - WTSClientDisplay, - WTSClientProtocolType, - WTSIdleTime, - WTSLogonTime, - WTSIncomingBytes, - WTSOutgoingBytes, - WTSIncomingFrames, - WTSOutgoingFrames, - WTSClientInfo, - WTSSessionInfo - } - - - [DllImport("wtsapi32.dll", SetLastError = true)] - public static extern int WTSEnumerateSessions( - System.IntPtr hServer, - int Reserved, - int Version, - ref System.IntPtr ppSessionInfo, - ref int pCount); - - [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)] - public static extern void WTSFreeMemory(IntPtr memory); - - [DllImport("Wtsapi32.dll")] - public static extern bool WTSQuerySessionInformation(IntPtr hServer, uint sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned); - - [DllImport("wtsapi32.dll", SetLastError = true)] - static extern IntPtr WTSOpenServer(string pServerName); - - [StructLayout(LayoutKind.Sequential)] - public struct WTS_SESSION_INFO - { - public uint SessionID; - [MarshalAs(UnmanagedType.LPStr)] - public string pWinStationName; - public WTS_CONNECTSTATE_CLASS State; - } - } -} diff --git a/Shared/Win32/Win32Interop.cs b/Shared/Win32/Win32Interop.cs deleted file mode 100644 index a6b51641f..000000000 --- a/Shared/Win32/Win32Interop.cs +++ /dev/null @@ -1,230 +0,0 @@ -using Remotely.Shared.Models; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using static Remotely.Shared.Win32.ADVAPI32; -using static Remotely.Shared.Win32.User32; - -namespace Remotely.Shared.Win32 -{ - // TODO: Use https://github.com/dotnet/pinvoke for all p/invokes. Remove signatures from this project. - public class Win32Interop - { - private static IntPtr _lastInputDesktop; - - public static List GetActiveSessions() - { - var sessions = new List(); - var consoleSessionId = Kernel32.WTSGetActiveConsoleSessionId(); - sessions.Add(new WindowsSession() - { - ID = consoleSessionId, - Type = SessionType.Console, - Name = "Console", - Username = GetUsernameFromSessionId(consoleSessionId) - }); - - IntPtr ppSessionInfo = IntPtr.Zero; - var count = 0; - var enumSessionResult = WTSAPI32.WTSEnumerateSessions(WTSAPI32.WTS_CURRENT_SERVER_HANDLE, 0, 1, ref ppSessionInfo, ref count); - var dataSize = Marshal.SizeOf(typeof(WTSAPI32.WTS_SESSION_INFO)); - var current = ppSessionInfo; - - if (enumSessionResult != 0) - { - for (int i = 0; i < count; i++) - { - WTSAPI32.WTS_SESSION_INFO sessionInfo = (WTSAPI32.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTSAPI32.WTS_SESSION_INFO)); - current += dataSize; - if (sessionInfo.State == WTSAPI32.WTS_CONNECTSTATE_CLASS.WTSActive && sessionInfo.SessionID != consoleSessionId) - { - - sessions.Add(new WindowsSession() - { - ID = sessionInfo.SessionID, - Name = sessionInfo.pWinStationName, - Type = SessionType.RDP, - Username = GetUsernameFromSessionId(sessionInfo.SessionID) - }); - } - } - } - - return sessions; - } - - public static string GetCommandLine() - { - var commandLinePtr = Kernel32.GetCommandLine(); - return Marshal.PtrToStringAuto(commandLinePtr); - } - - public static bool GetCurrentDesktop(out string desktopName) - { - var inputDesktop = OpenInputDesktop(); - try - { - byte[] deskBytes = new byte[256]; - if (!GetUserObjectInformationW(inputDesktop, UOI_NAME, deskBytes, 256, out uint lenNeeded)) - { - desktopName = string.Empty; - return false; - } - - desktopName = Encoding.Unicode.GetString(deskBytes.Take((int)lenNeeded).ToArray()).Replace("\0", ""); - return true; - } - finally - { - CloseDesktop(inputDesktop); - } - } - - public static string GetUsernameFromSessionId(uint sessionId) - { - var username = string.Empty; - - if (WTSAPI32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTSAPI32.WTS_INFO_CLASS.WTSUserName, out var buffer, out var strLen) && strLen > 1) - { - username = Marshal.PtrToStringAnsi(buffer); - WTSAPI32.WTSFreeMemory(buffer); - } - - return username; - } - - public static IntPtr OpenInputDesktop() - { - return User32.OpenInputDesktop(0, true, ACCESS_MASK.GENERIC_ALL); - } - - public static bool OpenInteractiveProcess(string applicationName, - int targetSessionId, - bool forceConsoleSession, - string desktopName, - bool hiddenWindow, - out PROCESS_INFORMATION procInfo) - { - uint winlogonPid = 0; - IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero; - procInfo = new PROCESS_INFORMATION(); - - // If not force console, find target session. If not present, - // use last active session. - var dwSessionId = Kernel32.WTSGetActiveConsoleSessionId(); - if (!forceConsoleSession) - { - var activeSessions = GetActiveSessions(); - if (activeSessions.Any(x => x.ID == targetSessionId)) - { - dwSessionId = (uint)targetSessionId; - } - else - { - dwSessionId = activeSessions.Last().ID; - } - } - - // Obtain the process ID of the winlogon process that is running within the currently active session. - Process[] processes = Process.GetProcessesByName("winlogon"); - foreach (Process p in processes) - { - if ((uint)p.SessionId == dwSessionId) - { - winlogonPid = (uint)p.Id; - } - } - - // Obtain a handle to the winlogon process. - hProcess = Kernel32.OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid); - - // Obtain a handle to the access token of the winlogon process. - if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken)) - { - Kernel32.CloseHandle(hProcess); - return false; - } - - // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser. - SECURITY_ATTRIBUTES sa = new(); - sa.Length = Marshal.SizeOf(sa); - - // Copy the access token of the winlogon process; the newly created token will be a primary token. - if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out hUserTokenDup)) - { - Kernel32.CloseHandle(hProcess); - Kernel32.CloseHandle(hPToken); - return false; - } - - // By default, CreateProcessAsUser creates a process on a non-interactive window station, meaning - // the window station has a desktop that is invisible and the process is incapable of receiving - // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user - // interaction with the new process. - STARTUPINFO si = new(); - si.cb = Marshal.SizeOf(si); - si.lpDesktop = @"winsta0\" + desktopName; - - // Flags that specify the priority and creation method of the process. - uint dwCreationFlags; - if (hiddenWindow) - { - dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW; - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = 0; - } - else - { - dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE; - } - - // Create a new process in the current user's logon session. - bool result = CreateProcessAsUser(hUserTokenDup, null, applicationName, ref sa, ref sa, false, dwCreationFlags, IntPtr.Zero, null, ref si, out procInfo); - - // Invalidate the handles. - Kernel32.CloseHandle(hProcess); - Kernel32.CloseHandle(hPToken); - Kernel32.CloseHandle(hUserTokenDup); - - return result; - } - - public static void SetMonitorState(MonitorState state) - { - SendMessage(0xFFFF, 0x112, 0xF170, (int)state); - } - - public static MessageBoxResult ShowMessageBox(IntPtr owner, - string message, - string caption, - MessageBoxType messageBoxType) - { - return (MessageBoxResult)MessageBox(owner, message, caption, (long)messageBoxType); - } - - public static bool SwitchToInputDesktop() - { - try - { - CloseDesktop(_lastInputDesktop); - var inputDesktop = OpenInputDesktop(); - - if (inputDesktop == IntPtr.Zero) - { - return false; - } - - var result = SetThreadDesktop(inputDesktop) && SwitchDesktop(inputDesktop); - _lastInputDesktop = inputDesktop; - return result; - } - catch - { - return false; - } - } - } -} diff --git a/submodules/Immense.RemoteControl b/submodules/Immense.RemoteControl index a896025eb..debde4e5a 160000 --- a/submodules/Immense.RemoteControl +++ b/submodules/Immense.RemoteControl @@ -1 +1 @@ -Subproject commit a896025ebf2f9cbcb2ae280f88a178acc39acfd2 +Subproject commit debde4e5a4ca08d37493632b76650d983b369352