using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Management; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace ScreenConnect; public static class WindowsExtensions { private enum ClientProtocolType : short { Console = 0, Rdp = 2 } [ComImport] [ClassInterface(0)] [TypeLibType(2)] [Guid("CB2F6723-AB3A-11D2-9C40-00C04FA30A3E")] private class CorRuntimeHostClass { } [ComImport] [ComConversionLoss] [Guid("CB2F6722-AB3A-11D2-9C40-00C04FA30A3E")] [InterfaceType(1)] private interface ICorRuntimeHost { void CreateLogicalThreadState(); void DeleteLogicalThreadState(); void SwitchInLogicalThreadState(); void SwitchOutLogicalThreadState(); void LocksHeldByLogicalThread(); void MapFile(); void GetConfiguration(); void Start(); void Stop(); void CreateDomain(); void GetDefaultDomain(); void EnumDomains(out IntPtr hEnum); void NextDomain(IntPtr hEnum, [MarshalAs(UnmanagedType.IUnknown)] out object pAppDomain); void CloseEnum(IntPtr hEnum); } private const LogonSessionAttributes BaseLogonSessionAttributes = LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasSendSystemKeyCodeCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability; private const LogonSessionAttributes BackstageCapabilitiesAttributes = LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability; private const LogonSessionAttributes RdpLogonSessionAttributes = LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability; public static void FixupProcess() { if (GetTrueOSVersion() >= new Version(6, 2)) { WindowsNative.SetDefaultDllDirectories(WindowsNative.LOAD_LIBRARY_SEARCH.SYSTEM32).AssertTrueOrThrowLastWin32Error("WindowsNative.SetDefaultDllDirectories(WindowsNative.LOAD_LIBRARY_SEARCH.SYSTEM32)"); try { SetProcessMitigationPolicy(WindowsNative.PROCESS_MITIGATION_POLICY.ProcessImageLoadPolicy, 4); } catch (Win32Exception ex) when (ex.NativeErrorCode == 87) { } } } public static void SetProcessMitigationPolicy(WindowsNative.PROCESS_MITIGATION_POLICY type, int policy) { WindowsNative.SetProcessMitigationPolicy(type, ref policy, new IntPtr(Marshal.SizeOf((object)policy))).AssertTrueOrThrowLastWin32Error("WindowsNative.SetProcessMitigationPolicy(type, ref policy, new IntPtr(Marshal.SizeOf(policy)))"); } public static HandleMinder OpenProcess(int processID, WindowsNative.ProcessAccess processAccess = WindowsNative.ProcessAccess.MAXIMUM_ALLOWED) { return HandleMinder.CreateWithFunc(WindowsNative.OpenProcess(processAccess, bInheritHandle: false, processID), WindowsNative.CloseHandle); } public static HandleMinder OpenCurrentProcess() { return HandleMinder.CreateWithFunc(WindowsNative.GetCurrentProcess(), WindowsNative.CloseHandle); } public static HandleMinder OpenProcessToken(IntPtr processHandle, WindowsNative.TOKEN tokenAccess = WindowsNative.TOKEN.MAXIMUM_ALLOWED) { return HandleMinder.CreateWithFunc(WindowsNative.OpenProcessToken, WindowsNative.CloseHandle, processHandle, tokenAccess); } public static HandleMinder OpenProcessToken(int processID, WindowsNative.ProcessAccess processAccess = WindowsNative.ProcessAccess.MAXIMUM_ALLOWED, WindowsNative.TOKEN tokenAccess = WindowsNative.TOKEN.MAXIMUM_ALLOWED) { using HandleMinder handleMinder = OpenProcess(processID, processAccess); return OpenProcessToken(handleMinder, tokenAccess); } public static HandleMinder DuplicateToken(HandleMinder htoken) { htoken.AssertArgumentNonNull("htoken"); return HandleMinder.CreateWithFunc(WindowsNative.DuplicateTokenEx, WindowsNative.CloseHandle, htoken.Handle, WindowsNative.TOKEN.TOKEN_ALL_ACCESS, IntPtr.Zero, WindowsNative.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, WindowsNative.TOKEN_TYPE.TokenPrimary); } public static bool IsDropDownVisible(this ToolStripDropDownItem @this) { if (@this.HasDropDownItems) { return @this.DropDown.Visible; } return false; } public static IDisposable ImpersonateLoggedOnUser(IntPtr tokenHandle) { if (!WindowsNative.ImpersonateLoggedOnUser(tokenHandle)) { throw new InvalidOperationException(); } return new ProcDisposable(delegate { WindowsNative.RevertToSelf(); }); } public static T InvokeAsLoggedOnUser(Func function) { if (GetTrueOSVersion() < new Version(5, 1)) { throw new NotSupportedException(); } if (!WindowsNative.WTSQueryUserToken(GetCurrentProcessSessionID(), out var phToken)) { throw new InvalidOperationException(); } using HandleMinder htoken = HandleMinder.CreateWithFunc(phToken, WindowsNative.CloseHandle); using HandleMinder handleMinder = DuplicateToken(htoken); using (ImpersonateLoggedOnUser(handleMinder)) { return function(); } } public static HandleMinder OpenServiceControlManager() { return HandleMinder.CreateWithFunc(WindowsNative.OpenSCManager(null, null, 983103), WindowsNative.CloseServiceHandle); } public static HandleMinder OpenService(HandleMinder hscm, string serviceName) { return HandleMinder.CreateWithFunc(WindowsNative.OpenService(hscm, serviceName, 983551), WindowsNative.CloseServiceHandle, 1060); } public static void UpdateServiceClientLaunchParametersInMemoryAndRegistry(string serviceName, ClientLaunchParameters memoryClientLaunchParameters) { if (memoryClientLaunchParameters.EncryptedGuestClientValidationKey != null) { return; } if (!ApplicationSettings.Instance.AccessGuestVerificationKey.IsNullOrEmpty()) { memoryClientLaunchParameters.EncryptedGuestClientValidationKey = ApplicationSettings.Instance.AccessGuestVerificationKey; } else { using RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(2048); memoryClientLaunchParameters.EncryptedGuestClientValidationKey = Singleton.Instance.ProtectBytes(rSACryptoServiceProvider.ExportCspBlob(includePrivateParameters: true)); } using RegistryKey registryKey = OpenServiceRegistryKey(serviceName, writable: true); if (registryKey == null) { return; } string[] array = ((string)registryKey.GetValue("ImagePath", string.Empty)).Split(new char[0]); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(new char[1] { '"' }); if (!text.StartsWith("?")) { continue; } ClientLaunchParameters clientLaunchParameters = ClientLaunchParameters.FromQueryStringWithoutConstraint(text); if (clientLaunchParameters.SessionID == memoryClientLaunchParameters.SessionID) { if (!clientLaunchParameters.EncryptedGuestClientValidationKey.IsNullOrEmpty()) { memoryClientLaunchParameters.EncryptedGuestClientValidationKey = clientLaunchParameters.EncryptedGuestClientValidationKey; break; } clientLaunchParameters.EncryptedGuestClientValidationKey = memoryClientLaunchParameters.EncryptedGuestClientValidationKey; array[i] = "\"" + clientLaunchParameters.ToQueryString() + "\""; registryKey.SetValue("ImagePath", array.Join(" ")); } break; } } public static RegistryKey OpenServiceRegistryKey(string serviceName, bool writable) { return Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\" + serviceName, writable); } public static void EnableCurrentProcessPrivilege(string privilegeName) { using HandleMinder handleMinder = OpenCurrentProcess(); using HandleMinder handleMinder2 = OpenProcessToken(handleMinder.Handle, WindowsNative.TOKEN.TOKEN_QUERY | WindowsNative.TOKEN.TOKEN_ADJUST_PRIVILEGES); AdjustTokenPrivilege(handleMinder2, privilegeName, enabledOrDisabled: true); } public static void AdjustTokenPrivilege(IntPtr token, string privilegeName, bool enabledOrDisabled) { WindowsNative.TOKEN_PRIVILEGES NewState = CreateTokenPrivileges(privilegeName, enabledOrDisabled); if (!WindowsNative.AdjustTokenPrivileges(token, DisableAllPrivileges: false, ref NewState, 0u, IntPtr.Zero, IntPtr.Zero)) { ThrowLastError(); } } public static WindowsNative.TOKEN_PRIVILEGES CreateTokenPrivileges(string privilegeName, bool enabledOrDisabled) { if (!WindowsNative.LookupPrivilegeValue(null, privilegeName, out var lpLuid)) { ThrowLastError(); } WindowsNative.TOKEN_PRIVILEGES result = default(WindowsNative.TOKEN_PRIVILEGES); result.PrivilegeCount = 1u; result.Luid = lpLuid; result.Attributes = (enabledOrDisabled ? 2u : 4u); return result; } public static FileSystemAccessRule GetFileSystemAccessRule(IdentityReference identity, FileSystemRights fileSystemRights, bool enableInheritance) { return new FileSystemAccessRule(identity, fileSystemRights, enableInheritance ? (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit) : InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow); } public static FileSystemAccessRule GetFileSystemAccessRule(WellKnownSidType sidType, FileSystemRights fileSystemRights, bool enableInheritance) { return GetFileSystemAccessRule(new SecurityIdentifier(sidType, null), fileSystemRights, enableInheritance); } public static void EnsureDirectoryEmptyAndRestricted(string directoryPath) { DirectorySecurity directorySecurity = new DirectorySecurity(); directorySecurity.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent()) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); SecurityIdentifier securityIdentifier2 = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); SecurityIdentifier securityIdentifier3 = windowsIdentity.User ?? securityIdentifier; directorySecurity.SetOwner(securityIdentifier3); SecurityIdentifier[] array = new SecurityIdentifier[3] { securityIdentifier3, securityIdentifier, securityIdentifier2 }; foreach (SecurityIdentifier identity in array) { directorySecurity.AddAccessRule(GetFileSystemAccessRule(identity, FileSystemRights.FullControl, enableInheritance: true)); } } DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath); if (directoryInfo.Exists) { directoryInfo.SetAccessControl(directorySecurity); } else { directoryInfo.Create(directorySecurity); } directoryInfo.DeleteContents(); } public static string DemandEmptyAndRestrictedDirectoryPath(string baseDirectoryPath) { try { EnsureDirectoryEmptyAndRestricted(baseDirectoryPath); return baseDirectoryPath; } catch { string text = $"{baseDirectoryPath}-{Guid.NewGuid()}"; EnsureDirectoryEmptyAndRestricted(text); return text; } } public static int? TryLookupLsaAuthenticationPackage(string packageName) { if (WindowsNative.LsaConnectUntrusted(out var LsaHandle) != 0) { return null; } WindowsNative.LSA_STRING PackageName = new WindowsNative.LSA_STRING { Length = (ushort)packageName.Length, MaximumLength = (ushort)(packageName.Length + 1), Buffer = Marshal.StringToHGlobalAnsi(packageName) }; try { uint AuthenticationPackage; return (WindowsNative.LsaLookupAuthenticationPackage(LsaHandle, ref PackageName, out AuthenticationPackage) == 0) ? new int?((int)AuthenticationPackage) : ((int?)null); } finally { Marshal.FreeHGlobal(PackageName.Buffer); WindowsNative.LsaDeregisterLogonProcess(LsaHandle); } } public unsafe static (string? Domain, string? UserName) GetLsaLogonSessionDomainAndUserName(ulong logonSessionID) { WindowsNative.SECURITY_LOGON_SESSION_DATA* ptr = default(WindowsNative.SECURITY_LOGON_SESSION_DATA*); if (WindowsNative.LsaGetLogonSessionData(&logonSessionID, &ptr) != 0) { return default((string, string)); } try { return (Domain: Marshal.PtrToStringUni(ptr->LogonDomain.Buffer, ptr->LogonDomain.Length / 2), UserName: Marshal.PtrToStringUni(ptr->UserName.Buffer, ptr->UserName.Length / 2)); } finally { WindowsNative.LsaFreeReturnBuffer(ptr); } } public static WindowsNative.WTS_CONNECTSTATE_CLASS GetSessionConnectionState(int sessionID) { return QuerySessionInformation(sessionID, WindowsNative.WTS_INFO_CLASS.WTSConnectState).To(); } public static string GetSessionUserName(int sessionID) { return QuerySessionInformation(sessionID, WindowsNative.WTS_INFO_CLASS.WTSUserName); } public static string GetSessionUserDomain(int sessionID) { return QuerySessionInformation(sessionID, WindowsNative.WTS_INFO_CLASS.WTSDomainName); } private static ClientProtocolType GetSessionProtocolType(int sessionID) { return QuerySessionInformation(sessionID, WindowsNative.WTS_INFO_CLASS.WTSClientProtocolType).To(); } private static T QuerySessionInformation(int sessionID, WindowsNative.WTS_INFO_CLASS infoClass) where T : notnull { WindowsNative.WTSQuerySessionInformation(IntPtr.Zero, sessionID, infoClass, out var ppBuffer, out var _).AssertTrueOrThrowLastWin32Error("WindowsNative.WTSQuerySessionInformation(IntPtr.Zero, sessionID, infoClass, out var outPtr, out _)"); try { if ((object)typeof(T) == typeof(int)) { return (T)(object)Marshal.ReadInt32(ppBuffer); } if ((object)typeof(T) == typeof(short)) { return (T)(object)Marshal.ReadInt16(ppBuffer); } if ((object)typeof(T) == typeof(string)) { return (T)(object)Marshal.PtrToStringAuto(ppBuffer); } throw new ArgumentOutOfRangeException("T"); } finally { WindowsNative.WTSFreeMemory(ppBuffer); } } public static int? TryGetActiveConsoleSessionID() { Version trueOSVersion = GetTrueOSVersion(); if (trueOSVersion < new Version(5, 1)) { return 0; } bool flag = trueOSVersion < new Version(6, 0); bool flag2; if (flag) { WindowsNative.WTS_CONNECTSTATE_CLASS? wTS_CONNECTSTATE_CLASS = Extensions.TryGetNullable(() => GetSessionConnectionState(0)); if (wTS_CONNECTSTATE_CLASS.HasValue) { WindowsNative.WTS_CONNECTSTATE_CLASS valueOrDefault = wTS_CONNECTSTATE_CLASS.GetValueOrDefault(); if ((uint)valueOrDefault <= 1u) { flag2 = true; goto IL_0070; } } flag2 = false; goto IL_0070; } goto IL_0073; IL_0070: flag = flag2; goto IL_0073; IL_0073: if (flag) { return 0; } return WindowsNative.WTSGetActiveConsoleSessionId().Pipe((int it) => (it != -1) ? new int?(it) : ((int?)null)); } public static IList<(int SessionID, string Name, string UserName)>? TryGetValidSessionInfos() { if (GetTrueOSVersion() < new Version(5, 1)) { return (0, "Console", GetLoggedOnUserName(0) ?? string.Empty).ToSingleElementArray(); } int? activeConsoleSessionID = TryGetActiveConsoleSessionID(); if (activeConsoleSessionID.HasValue) { (int, string, string, string, bool)[] sessionInfos = GetSessionInfos(); if (sessionInfos.None(((int SessionID, string Name, string UserName, string UserDomain, bool IsActiveOrConnected) _) => _.SessionID == activeConsoleSessionID)) { return null; } return (from it in sessionInfos where it.IsActiveOrConnected select (SessionID: it.SessionID, Name: it.Name, it.UserName ?? string.Empty)).ToList(); } return null; } public unsafe static (int SessionID, string Name, string? UserName, string? UserDomain, bool IsActiveOrConnected)[] GetSessionInfos() { WindowsNative.WTS_SESSION_INFO* ptr = default(WindowsNative.WTS_SESSION_INFO*); int num = 0; WindowsNative.WTSEnumerateSessions(IntPtr.Zero, 0, 1, &ptr, &num).AssertTrueOrThrowLastWin32Error("WindowsNative.WTSEnumerateSessions(IntPtr.Zero, 0, 1, &sessionInfos, &count)"); try { (int, string, string, string, bool)[] array = new(int, string, string, string, bool)[num]; for (int i = 0; i < num; i++) { (int, string, string, string, bool)[] array2 = array; int num2 = i; int sessionId = ptr[i].SessionId; string item = new string(ptr[i].pWinStationName); string item2 = ptr[i].SessionId.TryPipe(GetSessionUserName); string item3 = ptr[i].SessionId.TryPipe(GetSessionUserDomain); WindowsNative.WTS_CONNECTSTATE_CLASS state = ptr[i].State; bool item4 = (uint)state <= 1u; array2[num2] = (sessionId, item, item2, item3, item4); } return array; } finally { WindowsNative.WTSFreeMemory((IntPtr)ptr); } } public static LogonSessionInfo2 GetLogonSessionInfo(int logonSessionID, string displayName, bool isBackstageOrUserLogonSession, bool isDefaultLogonSession) { return new LogonSessionInfo2 { LogonSessionID = logonSessionID.ToString(), DisplayName = displayName, LogonSessionAttributes = (LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasSendSystemKeyCodeCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability).EnsureFlags((!isBackstageOrUserLogonSession) ? LogonSessionAttributes.UserLogonSession : LogonSessionAttributes.BackstageLogonSession, setOrUnset: true).EnsureFlags(LogonSessionAttributes.DefaultLogonSession, isDefaultLogonSession).EnsureFlagsIf(LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasSendSystemKeyCodeCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability, LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability, isBackstageOrUserLogonSession) .EnsureFlagsIf(LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasSendSystemKeyCodeCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability, LogonSessionAttributes.HasRenderScreenCapability | LogonSessionAttributes.HasNormalModeRebootCapability | LogonSessionAttributes.HasSafeModeRebootCapability | LogonSessionAttributes.HasBlockGuestInputCapability | LogonSessionAttributes.HasReceiveGuestFolderCapability | LogonSessionAttributes.HasSendMessageCapability, GetSessionProtocolType(logonSessionID) == ClientProtocolType.Rdp) }; } public static string GetLoggedOnUserName(int sessionID) { GetLoggedOnUserInfo(sessionID, out var _, out var userName); return userName; } public static void GetLoggedOnUserInfo(out string userDomain, out string userName) { GetLoggedOnUserInfo(GetSessionID(WindowsNative.GetCurrentProcessId()), out userDomain, out userName); } public static void GetLoggedOnUserInfo(int sessionID, out string userDomain, out string userName) { bool flag = GetTrueOSVersion() >= new Version(5, 1); if (flag && WindowsNative.WTSQueryUserToken(sessionID, out var phToken)) { using (WindowsIdentity windowsIdentity = new WindowsIdentity(phToken)) { string[] array = windowsIdentity.Name.Split(new char[1] { '\\' }); userDomain = array.FirstOrDefault(); userName = array.LastOrDefault(); return; } } if (!flag || Marshal.GetLastWin32Error() == 5 || Marshal.GetLastWin32Error() == 1314) { userDomain = Environment.UserDomainName; userName = Environment.UserName; } else { userDomain = null; userName = null; } } public static IEnumerable GetProcessIDs() { int num = 9; int[] processIDs; int num2; int bytesCopied; do { processIDs = new int[1 << num++]; num2 = processIDs.Length * Marshal.SizeOf(typeof(int)); WindowsNative.EnumProcesses(processIDs, num2, out bytesCopied).AssertTrueOrThrowLastWin32Error("WindowsNative.EnumProcesses(processIDs, processIDsSize, out var bytesCopied)"); } while (bytesCopied >= num2); int processCount = bytesCopied / Marshal.SizeOf(typeof(int)); for (int i = 0; i < processCount; i++) { yield return processIDs[i]; } } public static IEnumerable GetProcessIDs(int sessionID) { foreach (int processID in GetProcessIDs()) { if (GetSessionID(processID) == sessionID) { yield return processID; } } } public static IEnumerable GetProcessIDs(int sessionID, WellKnownSidType wellKnownSidType) { foreach (int processID in GetProcessIDs(sessionID)) { if (IsProcessByUser(processID, wellKnownSidType)) { yield return processID; } } } public static SecurityIdentifier GetProcessUser(int processID) { using HandleMinder handleMinder = OpenProcessToken(processID); using WindowsIdentity windowsIdentity = new WindowsIdentity(handleMinder); return windowsIdentity.User; } public static bool IsProcessByUser(int processID, WellKnownSidType wellKnownSidType) { try { return GetProcessUser(processID).IsWellKnown(wellKnownSidType); } catch { return false; } } public static void KillProcessTree(int processID) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher("SELECT ProcessId, ParentProcessId FROM Win32_Process"); try { Dictionary> dictionary = new Dictionary>(); ManagementObjectEnumerator enumerator = val.Get().GetEnumerator(); try { while (enumerator.MoveNext()) { ManagementBaseObject current = enumerator.Current; ManagementBaseObject val2 = current; try { int item = (int)(uint)current["ProcessId"]; int key = (int)(uint)current["ParentProcessId"]; if (!dictionary.TryGetValue(key, out var value)) { value = new List(); dictionary.Add(key, value); } value.Add(item); } finally { ((IDisposable)val2)?.Dispose(); } } } finally { ((IDisposable)enumerator)?.Dispose(); } KillDescendentProcesses(processID, dictionary); } finally { ((IDisposable)val)?.Dispose(); } } private static void KillDescendentProcesses(int processID, Dictionary> parentToChildrenMap) { IList value = null; if (parentToChildrenMap.TryGetValue(processID, out value)) { foreach (int item in value) { KillDescendentProcesses(item, parentToChildrenMap); } } Extensions.Try(delegate { Process.GetProcessById(processID).Kill(); }); } public static void StartProcessInSameDirectory(string exePath, string args = null, bool shouldElevate = false) { Process process = new Process(); process.StartInfo.FileName = exePath; process.StartInfo.Arguments = args; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(exePath); if (shouldElevate) { if (Enumerable.Contains(process.StartInfo.Verbs, "runas")) { process.StartInfo.Verb = "runas"; } process.StartInfo.UseShellExecute = true; } process.Start(); } public static string RunCommandLineProgram(string exePath, string args = null, string standardInputString = null, int timeoutMilliseconds = -1, int maxResultLength = 0, bool throwOnNonZeroExitCode = true) { using Process process = new Process(); if (GetTrueOSVersion() >= new Version(6, 1)) { if (WindowsNative.AllocConsole()) { process.Disposed += delegate { WindowsNative.FreeConsole(); }; } WindowsNative.SetConsoleOutputCP(Encoding.UTF8.CodePage); process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; } process.StartInfo.FileName = exePath; process.StartInfo.Arguments = args; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = standardInputString != null; process.StartInfo.UseShellExecute = false; process.Start(); if (standardInputString != null) { process.StandardInput.Write(standardInputString); process.StandardInput.Flush(); process.StandardInput.Close(); } List list = new List { new ManualResetEvent(initialState: false) { SafeWaitHandle = new SafeWaitHandle(process.Handle, ownsHandle: false) } }; StringBuilder resultBuilder = new StringBuilder(); char[] charBuffer = new char[4096]; StreamReader[] array = new StreamReader[2] { process.StandardOutput, process.StandardError }; foreach (StreamReader streamReader in array) { Stream stream = streamReader.BaseStream; Decoder decoder = streamReader.CurrentEncoding.GetDecoder(); byte[] buffer = new byte[4096]; AsyncCallback processResultProc = null; ManualResetEvent waitHandle = new ManualResetEvent(initialState: false); list.Add(waitHandle); processResultProc = delegate(IAsyncResult result) { try { int num2 = stream.EndRead(result); int num3 = 0; int num4 = num2; lock (resultBuilder) { while (true) { int num5 = charBuffer.Length; if (maxResultLength != 0) { num5 = Math.Min(maxResultLength - resultBuilder.Length, num5); } if (num5 <= 0) { break; } decoder.Convert(buffer, num3, num4, charBuffer, 0, num5, flush: false, out var bytesUsed, out var charsUsed, out var completed); resultBuilder.Append(charBuffer, 0, charsUsed); num3 += bytesUsed; num4 -= bytesUsed; if (completed) { break; } if (maxResultLength != 0 && resultBuilder.Length == maxResultLength && num4 > 0) { resultBuilder.AppendLine(); resultBuilder.AppendLine(); resultBuilder.AppendFormat("Truncated output at {0} characters.", maxResultLength); } } } if (num2 > 0) { stream.BeginRead(buffer, 0, buffer.Length, processResultProc, null); } else { waitHandle.Set(); } } catch { waitHandle.Set(); } }; stream.BeginRead(buffer, 0, buffer.Length, processResultProc, null); } if (!WaitHandle.WaitAll(list.ToArray(), timeoutMilliseconds, exitContext: false)) { try { KillProcessTree(process.Id); process.StandardOutput.BaseStream.Close(); process.StandardError.BaseStream.Close(); } catch { } if (resultBuilder.Length != 0) { resultBuilder.AppendLine(); resultBuilder.AppendLine(); } resultBuilder.AppendFormat("Killed after {0} milliseconds.", timeoutMilliseconds); } if (throwOnNonZeroExitCode) { process.ExitCode.AssertWin32ResultZero(); } return resultBuilder.ToString().TrimStart(new char[3] { '\r', '\n', '\ufeff' }); } public static string RunCommandLineCommands(string commandText, string interpreterPath = "", int timeoutMilliseconds = -1, int maxResultLength = 0) { using (TryDisableFileSystemRedirectionTemporarily()) { string tempDirectoryPath = Extensions.TryGet(() => GetApplicationTempPath()) ?? GetLowIntegrityTempPath(); bool flag = interpreterPath.ContainsAnyIgnoreCase("powershell", "ps"); string uniqueTempPath = Extensions.GetUniqueTempPath(tempDirectoryPath, "run." + (flag ? "ps1" : "cmd")); try { using (FileStream stream = File.Create(uniqueTempPath, 4096, FileOptions.None)) { using StreamWriter streamWriter = new StreamWriter(stream, flag ? Encoding.UTF8 : Constants.UTF8EncodingWithoutPreamble); streamWriter.Write(commandText); } return RunCommandLineProgram(flag ? "WindowsPowershell\\v1.0\\powershell.exe" : "cmd.exe", (flag ? "-NoProfile -NonInteractive -ExecutionPolicy Unrestricted -File " : "/c ") + Extensions.QuoteWindowsCommandLine(uniqueTempPath), null, timeoutMilliseconds, maxResultLength, throwOnNonZeroExitCode: false); } finally { File.Delete(uniqueTempPath); } } } public static string GetLowIntegrityTempPath(bool shouldEnsureDirectoryExists = true) { string baseTempPath = Path.Combine(GetKnownFolderPath(Environment.SpecialFolder.UserProfile, IntPtr.Zero), "AppData\\LocalLow\\Temp"); return GetApplicationTempPath(shouldEnsureDirectoryExists, baseTempPath); } public static string GetApplicationTempPath(bool shouldEnsureDirectoryExists = true, string? baseTempPath = null) { return Extensions.CombinePaths(baseTempPath ?? GetTempPath(), "ScreenConnect", "25.6.9.9400").PassIf(FileSystemExtensions.EnsureDirectoryExists, shouldEnsureDirectoryExists); } public static string GetTempPath() { if (GetTrueOSVersion() >= new Version(10, 0, 20348)) { StringBuilder stringBuilder = new StringBuilder(261); int tempPath = WindowsNative.GetTempPath2(stringBuilder.Capacity, stringBuilder); if (tempPath <= 0) { throw CreateWin32Exception(Marshal.GetLastWin32Error()); } return Path.GetFullPath(stringBuilder.ToString(0, tempPath)); } using WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity.IsSystem) { string text = Environment.ExpandEnvironmentVariables("%SystemRoot%\\SystemTemp"); if (!Directory.Exists(text)) { EnsureDirectoryEmptyAndRestricted(text); } return text; } return Path.GetTempPath(); } public static Image ExtractEmbeddedResourceWithoutDpiSpecifierToImage(this Type classInAssembly, string resourceNameWithoutExtension) { return classInAssembly.ExtractEmbeddedResourceToStream(resourceNameWithoutExtension + ".png").SafeNav((Func)Image.FromStream) ?? classInAssembly.ExtractEmbeddedResourceToStream(resourceNameWithoutExtension + ".png").SafeNav((Func)Image.FromStream); } public static int GetCurrentProcessSessionID() { return GetSessionID(WindowsNative.GetCurrentProcessId()); } public static bool IsBackstageAvailable() { return GetTrueOSVersion() >= new Version(6, 0); } public static bool IsBackstage(int sessionID) { if (sessionID == 0) { return IsBackstageAvailable(); } return false; } public static bool IsBackstage() { return IsBackstage(GetCurrentProcessSessionID()); } public static int GetSessionID(int processID) { int pSessionId = 0; WindowsNative.ProcessIdToSessionId(processID, out pSessionId); return pSessionId; } public static Process TryGetProcess(int processID) { try { return Process.GetProcessById(processID); } catch { return null; } } public unsafe static (string Text, WindowsNative.MFT Types, WindowsNative.MFS States)? TryGetMenuItemInfo(IntPtr menuHandle, int menuItemIdentifier, bool byCommandOrByPosition = true) { WindowsNative.MENUITEMINFO mENUITEMINFO = new WindowsNative.MENUITEMINFO { cbSize = Marshal.SizeOf(typeof(WindowsNative.MENUITEMINFO)), fMask = (WindowsNative.MIIM.STATE | WindowsNative.MIIM.STRING | WindowsNative.MIIM.FTYPE) }; if (!WindowsNative.GetMenuItemInfo(menuHandle, menuItemIdentifier, !byCommandOrByPosition, &mENUITEMINFO)) { return null; } mENUITEMINFO.dwTypeData = Marshal.AllocHGlobal((mENUITEMINFO.cch + 1) * 2); mENUITEMINFO.cch++; try { WindowsNative.GetMenuItemInfo(menuHandle, menuItemIdentifier, !byCommandOrByPosition, &mENUITEMINFO); return (Marshal.PtrToStringUni(mENUITEMINFO.dwTypeData), mENUITEMINFO.fType, mENUITEMINFO.fState); } finally { Marshal.FreeHGlobal(mENUITEMINFO.dwTypeData); } } public static IDisposable ReplaceWndProc(IntPtr windowHandle, TUserData userData, Func newWndProc) { IntPtr oldWndProcPtr = default(IntPtr); WindowsNative.WndProc replaceWndProc = (IntPtr hwnd, WindowsNative.WM uMsg, IntPtr wParam, IntPtr lParam) => newWndProc(userData, (IntPtr hwnd2, WindowsNative.WM msg, IntPtr wParam2, IntPtr lParam2) => WindowsNative.CallWindowProc(oldWndProcPtr, hwnd2, msg, wParam2, lParam2), hwnd, uMsg, wParam, lParam); IntPtr functionPointerForDelegate = Marshal.GetFunctionPointerForDelegate((Delegate)replaceWndProc); oldWndProcPtr = SetWindowLongPtr(windowHandle, WindowsNative.GWL.WNDPROC, functionPointerForDelegate); return new ProcDisposable(delegate { GC.KeepAlive(replaceWndProc); SetWindowLongPtr(windowHandle, WindowsNative.GWL.WNDPROC, oldWndProcPtr); }); } public static IntPtr SetWindowLongPtr(IntPtr windowHandle, WindowsNative.GWL index, IntPtr value) { if (Marshal.SizeOf(typeof(int)) == 4) { return (IntPtr)WindowsNative.SetWindowLong(windowHandle, index, (int)value); } return WindowsNative.SetWindowLongPtr(windowHandle, index, value); } public static IntPtr GetWindowLongPtr(IntPtr windowHandle, WindowsNative.GWL index) { if (Marshal.SizeOf(typeof(int)) == 4) { return (IntPtr)WindowsNative.GetWindowLong(windowHandle, index); } return WindowsNative.GetWindowLongPtr(windowHandle, index); } public static Win32Exception CreateWin32Exception(int errorCode, string? callerExpression = null) { Win32Exception ex = new Win32Exception(errorCode); return new Win32Exception(errorCode, string.Format("{0} {1} - {2} - while executing `{3}`", new object[4] { "NativeErrorCode", errorCode, ex.Message, callerExpression ?? "" })); } public static bool AssertTrueOrThrowLastWin32Error(this bool @this, [CallerArgumentExpression("this")] string? callerName = null) { if (!@this) { throw CreateWin32Exception(Marshal.GetLastWin32Error(), callerName); } return @this; } public static void ThrowLastError(params int[] allowableCodes) { int lastWin32Error = Marshal.GetLastWin32Error(); if (Array.IndexOf(allowableCodes, lastWin32Error) == -1) { throw CreateWin32Exception(lastWin32Error); } } public static IntPtr AssertNonZeroOrThrowLastWin32Error(this IntPtr @this, [CallerArgumentExpression("this")] string? callerName = null) { if (!(@this != IntPtr.Zero)) { throw CreateWin32Exception(Marshal.GetLastWin32Error(), callerName); } return @this; } public static uint AssertNonZeroOrThrowLastWin32Error(this uint @this, [CallerArgumentExpression("this")] string? callerName = null) { if (@this == 0) { throw CreateWin32Exception(Marshal.GetLastWin32Error(), callerName); } return @this; } public static bool IsCurrentProcessTokenUnelevatedAdministrator() { uint cbSid = 256u; IntPtr intPtr = Marshal.AllocCoTaskMem((int)cbSid); try { if (GetCurrentProcessTokenInformation(WindowsNative.TOKEN_INFORMATION_CLASS.TokenElevationType) != 3) { return false; } HandleMinder handleMinder = HandleMinder.CreateWithFunc(GetCurrentProcessTokenInformation(WindowsNative.TOKEN_INFORMATION_CLASS.TokenLinkedToken), WindowsNative.CloseHandle); if (!WindowsNative.CreateWellKnownSid(WellKnownSidType.BuiltinAdministratorsSid, IntPtr.Zero, intPtr, ref cbSid)) { ThrowLastError(); } bool IsMember = false; if (!WindowsNative.CheckTokenMembership(handleMinder, intPtr, out IsMember)) { ThrowLastError(); } return IsMember; } catch (Exception ex) { TypeTrace.TraceException(ex); return false; } finally { Marshal.FreeCoTaskMem(intPtr); } } public static T GetCurrentProcessTokenInformation(WindowsNative.TOKEN_INFORMATION_CLASS tis) { using HandleMinder handleMinder = OpenCurrentProcess(); using HandleMinder handleMinder2 = OpenProcessToken(handleMinder.Handle, WindowsNative.TOKEN.TOKEN_QUERY | WindowsNative.TOKEN.TOKEN_ADJUST_PRIVILEGES); return GetTokenInformation(handleMinder2, tis); } public static T GetTokenInformation(IntPtr htoken, WindowsNative.TOKEN_INFORMATION_CLASS tis) { int ReturnLength = Marshal.SizeOf(typeof(T)); using NativeMemoryMinder nativeMemoryMinder = new NativeMemoryMinder(zeroMemoryOnAllocate: false, ReturnLength); if (!WindowsNative.GetTokenInformation(htoken, tis, nativeMemoryMinder.Address, ReturnLength, out ReturnLength)) { ThrowLastError(); } return (T)Marshal.PtrToStructure(nativeMemoryMinder.Address, typeof(T)); } public static bool TrySetTokenInformation(IntPtr htoken, WindowsNative.TOKEN_INFORMATION_CLASS tis, object value) { using NativeMemoryMinder nativeMemoryMinder = new NativeMemoryMinder(zeroMemoryOnAllocate: false, Marshal.SizeOf(value)); Marshal.StructureToPtr(value, nativeMemoryMinder.Address, fDeleteOld: false); return WindowsNative.SetTokenInformation(htoken, tis, nativeMemoryMinder.Address, nativeMemoryMinder.Size); } public static Process CreateProcessAsUser(string commandLine, IntPtr userToken, IDictionary newOrOverriddenEnvironmentVariables = null, string windowStationName = null, string desktopName = null) { userToken.AssertNotEquals(IntPtr.Zero); IntPtr intPtr = CreateEnvironmentBlock(userToken, newOrOverriddenEnvironmentVariables); WindowsNative.STARTUPINFO lpStartupInfo = new WindowsNative.STARTUPINFO { cb = Marshal.SizeOf(typeof(WindowsNative.STARTUPINFO)), wShowWindow = 5, dwFlags = WindowsNative.STARTUPINFO_FLAGS.STARTF_USESHOWWINDOW }; if (!windowStationName.IsNullOrEmpty() && !desktopName.IsNullOrEmpty()) { lpStartupInfo.lpDesktop = Marshal.StringToHGlobalUni(windowStationName + "\\" + desktopName); } WindowsNative.PROCESS_INFORMATION lpProcessInformation = default(WindowsNative.PROCESS_INFORMATION); try { if (!WindowsNative.CreateProcessAsUser(userToken, null, commandLine, IntPtr.Zero, IntPtr.Zero, bInheritHandles: false, WindowsNative.CreateProcessFlags.CREATE_NEW_CONSOLE | WindowsNative.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT, intPtr, null, ref lpStartupInfo, out lpProcessInformation)) { ThrowLastError(); } } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(lpStartupInfo.lpDesktop); WindowsNative.CloseHandle(lpProcessInformation.hThread); WindowsNative.CloseHandle(lpProcessInformation.hProcess); } return Process.GetProcessById(lpProcessInformation.dwProcessId); } private static IntPtr CreateEnvironmentBlock(IntPtr userToken, IDictionary newOrOverriddenEnvironmentVariables) { IntPtr intPtr = default(IntPtr); using HandleMinder handleMinder = HandleMinder.CreateWithFunc(WindowsNative.CreateEnvironmentBlock, WindowsNative.DestroyEnvironmentBlock, userToken, false); Dictionary dictionary = new Dictionary(newOrOverriddenEnvironmentVariables ?? new Dictionary()); foreach (string nullDelimitedString in GetNullDelimitedStrings(handleMinder)) { string[] array = nullDelimitedString.Split("=".ToCharArray(), 2); string key = array[0]; string value = array[1]; if (!dictionary.ContainsKey(key)) { dictionary[key] = value; } } return Marshal.StringToHGlobalUni(dictionary.Select((KeyValuePair variable) => variable.Key + "=" + variable.Value + "\0").Join("") + "\0"); } public static IDisposable TemporarilySwitchProcessToWindowStation(string windowStationName) { IntPtr originalProcessWindowStationHandle = WindowsNative.GetProcessWindowStation(); IntPtr temporaryWindowStationHandle = WindowsNative.OpenWindowStation(windowStationName, fInherit: true, WindowsNative.ACCESS_MASK.MAXIMUM_ALLOWED); if (!WindowsNative.SetProcessWindowStation(temporaryWindowStationHandle)) { ThrowLastError(); } return new ProcDisposable(delegate { if (!WindowsNative.SetProcessWindowStation(originalProcessWindowStationHandle)) { ThrowLastError(); } WindowsNative.CloseWindowStation(temporaryWindowStationHandle); }); } public static string GetSessionPipePath(int sessionID) { StringBuilder stringBuilder = new StringBuilder(255); int pReturnLength = 0; int[] array = new int[2] { 33, 34 }; foreach (int winStationInformationClass in array) { if (WindowsNative.WinStationQueryInformation(IntPtr.Zero, sessionID, winStationInformationClass, stringBuilder, stringBuilder.Capacity, out pReturnLength) && stringBuilder.Length != 0) { return stringBuilder.ToString(); } } return "\\\\.\\Pipe\\TerminalServer\\SystemExecSrvr\\" + sessionID; } public unsafe static Process CreateRemoteProcess(string commandLine, int sessionID) { using FileStream fileStream = new FileStream(WindowsNative.CreateFile(GetSessionPipePath(sessionID), 3221225472u, 0u, null, 3u, 0u, IntPtr.Zero), FileAccess.ReadWrite); WindowsNative._CPAU_PARAM structure = new WindowsNative._CPAU_PARAM { bInheritHandles = false, bUseDefaultToken = true, dwCreationFlags = 1032, dwProcessId = WindowsNative.GetCurrentProcessId(), StartupInfo = { wShowWindow = 5, cb = Marshal.SizeOf(typeof(WindowsNative.STARTUPINFO)) } }; byte[] bytes = Encoding.Unicode.GetBytes(commandLine); byte[] bytes2 = Encoding.Unicode.GetBytes("Winsta0\\Default"); int num = Marshal.SizeOf((object)structure); structure.lpCommandLine = (IntPtr)num; structure.StartupInfo.lpDesktop = (IntPtr)(num + bytes.Length + 2); structure.cbSize = num + bytes.Length + 2 + bytes2.Length + 2; fileStream.WriteStructure(ref structure); fileStream.Write(bytes, 0, bytes.Length); fileStream.WriteByte(0); fileStream.WriteByte(0); fileStream.Write(bytes2, 0, bytes2.Length); fileStream.WriteByte(0); fileStream.WriteByte(0); WindowsNative._CPAU_RET_PARAM structure2 = default(WindowsNative._CPAU_RET_PARAM); fileStream.ReadStructure(ref structure2); if (!structure2.bRetValue) { throw new InvalidOperationException(); } return Process.GetProcessById(structure2.ProcInfo.dwProcessId); } public static DesktopInfo OpenInputDesktop() { HandleMinder handleMinder = HandleMinder.CreateWithFunc(WindowsNative.OpenInputDesktop(0u, fInherit: false, WindowsNative.ACCESS_MASK.DESKTOP_ALL), WindowsNative.CloseDesktop); string desktopName = GetDesktopName(handleMinder); return new DesktopInfo(handleMinder, desktopName); } public static DesktopInfo GetCurrentThreadDesktop() { HandleMinder handleMinder = HandleMinder.Create(WindowsNative.GetThreadDesktop(WindowsNative.GetCurrentThreadId())); string desktopName = GetDesktopName(handleMinder); return new DesktopInfo(handleMinder, desktopName); } public static string GetCurrentThreadDesktopName() { using DesktopInfo desktopInfo = GetCurrentThreadDesktop(); return desktopInfo.Name; } public static void TryEnsureThreadOnInputDesktop() { Extensions.Try(delegate { using DesktopInfo desktopInfo = GetCurrentThreadDesktop(); using DesktopInfo desktopInfo2 = OpenInputDesktop(); if (desktopInfo.Name != desktopInfo2.Name) { SetThreadDesktop(desktopInfo2.Handle); } }); } public static string GetDesktopName(IntPtr desktopHandle) { StringBuilder stringBuilder = new StringBuilder(250); if (!WindowsNative.GetUserObjectInformation(desktopHandle, 2, stringBuilder, (uint)stringBuilder.Capacity, out var lpnLengthNeeded)) { ThrowLastError(); } while (lpnLengthNeeded > stringBuilder.Capacity) { stringBuilder.Capacity = (int)lpnLengthNeeded; if (!WindowsNative.GetUserObjectInformation(desktopHandle, 2, stringBuilder, (uint)stringBuilder.Capacity, out lpnLengthNeeded)) { ThrowLastError(); } } return stringBuilder.ToString(); } public static void SetThreadDesktop(IntPtr desktopHandle) { if (!WindowsNative.SetThreadDesktop(desktopHandle)) { ThrowLastError(); } } public static void SetProcessWindowStation(IntPtr windowStationHandle) { if (!WindowsNative.SetProcessWindowStation(windowStationHandle)) { ThrowLastError(); } } public static void SendLegacySystemKeyCode() { if (GetTrueOSVersion() >= new Version(6, 0)) { throw new InvalidOperationException(); } RunSyncOnNewThread(delegate { HandleMinder handleMinder = HandleMinder.CreateWithFunc(WindowsNative.OpenWindowStation("Winsta0", fInherit: false, WindowsNative.ACCESS_MASK.WINSTA_ALL_ACCESS), WindowsNative.CloseWindowStation); HandleMinder handleMinder2 = HandleMinder.Create(WindowsNative.GetProcessWindowStation()); try { SetProcessWindowStation(handleMinder); HandleMinder handleMinder3 = HandleMinder.CreateWithFunc(WindowsNative.OpenDesktop("Winlogon", 0u, fInherit: false, WindowsNative.ACCESS_MASK.DESKTOP_ALL), WindowsNative.CloseDesktop); HandleMinder handleMinder4 = HandleMinder.Create(WindowsNative.GetThreadDesktop(WindowsNative.GetCurrentThreadId())); try { SetThreadDesktop(handleMinder3); if (!WindowsNative.PostMessage((IntPtr)65535L, 786, IntPtr.Zero, (IntPtr)3014659)) { ThrowLastError(); } } finally { SetThreadDesktop(handleMinder4); } } finally { SetProcessWindowStation(handleMinder2); } }); } public static void RunSyncOnNewThread(Proc proc) { Exception exception = null; bool done = false; object syncLock = new object(); Singleton.Instance.StartThread("TempSyncThread", CorePriority.Normal, delegate { try { proc(); } catch (Exception ex) { exception = ex; } lock (syncLock) { done = true; Monitor.Pulse(syncLock); } }, null); lock (syncLock) { while (!done) { Monitor.Wait(syncLock); } } if (exception != null) { throw exception; } } public static IDisposable EnterCriticalSection(IntPtr lpCriticalSection) { WindowsNative.EnterCriticalSection(lpCriticalSection); return new ProcDisposable(delegate { WindowsNative.LeaveCriticalSection(lpCriticalSection); }); } public static IDisposable EnterMutex(string mutexName) { Mutex mutex = new Mutex(initiallyOwned: false, mutexName); mutex.WaitOne(); return new ProcDisposable(delegate { mutex.ReleaseMutex(); mutex.Close(); }); } public static string GetKnownFolderPath(Environment.SpecialFolder folder, IntPtr htoken) { StringBuilder stringBuilder = new StringBuilder(260); WindowsNative.SHGetFolderPath(IntPtr.Zero, folder, htoken, 0u, stringBuilder); return stringBuilder.ToString(); } public static PixelFormat GetDefaultPixelFormat(int bitsPerPixel) { return (PixelFormat)(bitsPerPixel switch { 32 => 139273, 24 => 137224, 16 => 135174, 8 => 198659, _ => throw new ArgumentException("Invalid bits per pixel."), }); } public static IntPtr GetHBitmap(ArraySegment bytes) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected I4, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) Bitmap val = (Bitmap)Image.FromStream((Stream)bytes.ToMemoryStream()); try { PixelModel pixelModel = new PixelModel((((Image)val).PixelFormat & 0xFF00) >> 8); using RawBitmap rawBitmap = new RawBitmap(pixelModel, ((Image)val).Width, ((Image)val).Height, Extensions.DivUp(((Image)val).Width * pixelModel.BitsPerPixel, 16) * 2); BitmapData val2 = val.LockBits(new Rectangle(default(Point), ((Image)val).Size), (ImageLockMode)3, ((Image)val).PixelFormat); new BitmapSection(pixelModel, val2.Width, val2.Height, val2.Stride, val2.Scan0).CopyPixels(rawBitmap); val.UnlockBits(val2); return WindowsNative.CreateBitmap(((Image)val).Width, ((Image)val).Height, 1, pixelModel.BitsPerPixel, rawBitmap.Scan0); } finally { ((IDisposable)val)?.Dispose(); } } public static int GetBitsPerPixel(PixelFormat pixelFormat) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected I4, but got Unknown return (pixelFormat & 0xFF00) >> 8; } public static Bitmap GetFileIcon(string path) { return GetIcon(path, isDirectory: false, shouldIgnoreActualFileOnDisk: false); } public static Bitmap GetTheoreticalDirectoryIcon() { return GetIcon("dummyNonEmptyDirectoryNameSoWeDontGetAHardDriveIcon", isDirectory: true, shouldIgnoreActualFileOnDisk: true); } public static Bitmap GetTheoreticalFileIcon(string fileExtension) { return GetIcon("dummyFileName" + fileExtension.EnsureStartsWithChar('.'), isDirectory: false, shouldIgnoreActualFileOnDisk: true); } private static Bitmap GetIcon(string path, bool isDirectory, bool shouldIgnoreActualFileOnDisk) { string pszPath = path.ConvertBothSlashesToChar(Path.DirectorySeparatorChar).AssertArgumentNonNull("path"); WindowsNative.SHFILEINFO psfi = default(WindowsNative.SHFILEINFO); WindowsNative.SHGetFileInfo(pszPath, isDirectory ? 16u : 128u, ref psfi, Marshal.SizeOf(typeof(WindowsNative.SHFILEINFO)), (WindowsNative.SHGFI)(0x101 | (shouldIgnoreActualFileOnDisk ? 16 : 0))); if (psfi.hIcon == (IntPtr)0) { return null; } try { return Icon.FromHandle(psfi.hIcon).ToBitmap(); } finally { WindowsNative.DestroyIcon(psfi.hIcon); } } public unsafe static SafeFileHandle CreateLocalNamedPipe(string pipeName, bool readOrWrite, int maxInstances = 1) { return WindowsNative.CreateNamedPipe("\\\\.\\pipe\\" + pipeName, readOrWrite ? WindowsNative.PIPE_ACCESS.INBOUND : WindowsNative.PIPE_ACCESS.OUTBOUND, (GetTrueOSVersion() >= new Version(6, 0)) ? WindowsNative.PIPE_MODE.REJECT_REMOTE_CLIENTS : ((WindowsNative.PIPE_MODE)0), maxInstances, 16384, 16384, 0, null); } public unsafe static SafeFileHandle CreateSecureLocalNamedPipe(string pipeName, bool readOrWrite, bool restrictToSystem, int maxInstances = 1) { FileSecurity fileSecurity = new FileSecurity(); SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); fileSecurity.SetAccessRule(GetFileSystemAccessRule(securityIdentifier, FileSystemRights.FullControl, enableInheritance: false)); if (restrictToSystem) { fileSecurity.SetOwner(securityIdentifier); } fixed (byte* securityDescriptorBinaryForm = fileSecurity.GetSecurityDescriptorBinaryForm()) { WindowsNative.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = new WindowsNative.SECURITY_ATTRIBUTES { nLength = WindowsNative.SecurityAttributesSize, lpSecurityDescriptor = (IntPtr)securityDescriptorBinaryForm }; return WindowsNative.CreateNamedPipe("\\\\.\\pipe\\" + pipeName, readOrWrite ? WindowsNative.PIPE_ACCESS.INBOUND : WindowsNative.PIPE_ACCESS.OUTBOUND, WindowsNative.PIPE_MODE.REJECT_REMOTE_CLIENTS, maxInstances, 16384, 16384, 0, &sECURITY_ATTRIBUTES); } } public unsafe static SafeFileHandle CreateFileOnNamedPipe(string pipeName, bool readOrWrite) { return WindowsNative.CreateFile("\\\\.\\pipe\\" + pipeName, readOrWrite ? 2147483648u : 1073741824u, 0u, null, 3u, 0u, IntPtr.Zero); } public unsafe static bool ConnectNamedPipe(SafeFileHandle pipeHandle) { if (!WindowsNative.ConnectNamedPipe(pipeHandle, null)) { return Marshal.GetLastWin32Error() == 535; } return true; } public static (BinaryReader, BinaryWriter) ConnectServerClientNamedPipes(string pipeID, bool serverOrClient, Func shouldStopWaitingToConnectFunc) { string pipeName = pipeID + "ServerRead"; string pipeName2 = pipeID + "ServerWrite"; SafeFileHandle safeFileHandle; SafeFileHandle safeFileHandle2; if (serverOrClient) { safeFileHandle = CreateAndConnectNamedPipe(pipeName, readOrWrite: true); safeFileHandle2 = CreateAndConnectNamedPipe(pipeName2, readOrWrite: false); } else { safeFileHandle2 = WaitAndConnectNamedPipe(pipeName, readOrWrite: false, shouldStopWaitingToConnectFunc); safeFileHandle = WaitAndConnectNamedPipe(pipeName2, readOrWrite: true, shouldStopWaitingToConnectFunc); } if (safeFileHandle.IsInvalid || safeFileHandle2.IsInvalid) { ThrowLastError(); } return (new BinaryReader(new FileStream(safeFileHandle, FileAccess.Read, 4096)), new BinaryWriter(new FileStream(safeFileHandle2, FileAccess.Write, 4096))); unsafe static SafeFileHandle CreateAndConnectNamedPipe(string pipeName3, bool readOrWrite) { SafeFileHandle safeFileHandle3 = CreateLocalNamedPipe(pipeName3, readOrWrite); WindowsNative.ConnectNamedPipe(safeFileHandle3, null); return safeFileHandle3; } static SafeFileHandle WaitAndConnectNamedPipe(string text, bool readOrWrite, Func func) { while (!WindowsNative.WaitNamedPipe("\\\\.\\pipe\\" + text, 10) && !func()) { Thread.Sleep(10); } return CreateFileOnNamedPipe(text, readOrWrite); } } public unsafe static string GetWindowClassName(IntPtr hwnd) { char* ptr = stackalloc char[256]; WindowsNative.GetClassName(hwnd, ptr, 256); return new string(ptr); } public static WindowsNative.WS GetWindowStyles(this Control control) { return (WindowsNative.WS)WindowsNative.GetWindowLong(control.Handle, WindowsNative.GWL.STYLE); } public static WindowsNative.WS_EX GetWindowStylesEx(this Control control) { return (WindowsNative.WS_EX)WindowsNative.GetWindowLong(control.Handle, WindowsNative.GWL.EXSTYLE); } public static void SetWindowStyles(this Control control, WindowsNative.WS styles) { WindowsNative.SetWindowLong(control.Handle, WindowsNative.GWL.STYLE, (int)styles); } public static void SetWindowStylesEx(this Control control, WindowsNative.WS_EX stylesEx) { WindowsNative.SetWindowLong(control.Handle, WindowsNative.GWL.EXSTYLE, (int)stylesEx); } public static IWin32Window GetTopMostMessageBoxOwner(Control possibleOwner) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (IWin32Window)(((object)possibleOwner) ?? ((object)new Form { TopMost = true, StartPosition = (FormStartPosition)1 })); } public static byte[]? ProtectString(string? unprotectedString, Guid entropy = default(Guid)) { return ProtectBytes(unprotectedString.SafePipe((string it) => Encoding.Default.GetBytes(it)), entropy); } public static byte[]? ProtectBytes(byte[]? unprotectedBytes, Guid entropy = default(Guid)) { if (unprotectedBytes == null) { return null; } return ProtectedData.Protect(unprotectedBytes, (entropy == default(Guid)) ? null : entropy.ToByteArray(), (DataProtectionScope)0); } public static string? TryUnprotectString(byte[]? protectedBytes, Guid entropy = default(Guid)) { return TryUnprotectBytes(protectedBytes, entropy).SafePipe((byte[] it) => Encoding.Default.GetString(it)); } public static byte[]? TryUnprotectBytes(byte[]? protectedBytes, Guid entropy = default(Guid)) { if (protectedBytes == null) { return null; } try { return ProtectedData.Unprotect(protectedBytes, (entropy == default(Guid)) ? null : entropy.ToByteArray(), (DataProtectionScope)0); } catch (Exception ex) { TypeTrace.TraceException(ex); return null; } } public static string GetRegistryString(RegistryKey baseKey, string keyPath, string valueName) { using RegistryKey registryKey = baseKey.OpenSubKey(keyPath); return (registryKey == null) ? null : (registryKey.GetValue(valueName) as string); } public static string GetLocalMachineRegistryString(string keyPath, string valueName) { using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(keyPath); return (registryKey == null) ? null : (registryKey.GetValue(valueName) as string); } public static string TryGetLocalMachineRegistryString(string keyPath, string valueName) { return Extensions.TryGet(() => GetLocalMachineRegistryString(keyPath, valueName)); } private static int GetRegistryKeyFlags(bool canRead, bool canWrite, bool disableWow64Redirection) { return ((disableWow64Redirection && GetTrueOSVersion() >= new Version(5, 1)) ? 256 : 0) | (canRead ? 131097 : 0) | (canWrite ? 131078 : 0); } public static HandleMinder OpenRegistryKey(IntPtr baseKeyHandle, string subKeyPath, bool canRead = true, bool canWrite = true, bool disableWow64Redirection = true) { return HandleMinder.CreateWithIntFunc(WindowsNative.RegOpenKeyEx, WindowsNative.RegCloseKey, baseKeyHandle, subKeyPath, 0, GetRegistryKeyFlags(canRead, canWrite, disableWow64Redirection)); } public static HandleMinder OpenOrCreateRegistryKey(IntPtr baseKeyHandle, string subKeyPath, bool canRead = true, bool canWrite = true, bool disableWow64Redirection = true) { WindowsNative.RegCreateKeyEx(baseKeyHandle, subKeyPath, 0, null, 0, GetRegistryKeyFlags(canRead, canWrite, disableWow64Redirection), (IntPtr)0, out var phkResult, out var _).AssertWin32ResultZero(); return HandleMinder.CreateWithProc(phkResult, delegate(IntPtr handle) { WindowsNative.RegCloseKey(handle); }); } public static void GetSystemMemoryInformation(out int memoryLoad, out long totalPhysicalMemory, out long availablePhysicalMemory) { WindowsNative.MEMORYSTATUSEX lpBuffer = default(WindowsNative.MEMORYSTATUSEX); lpBuffer.dwLength = (uint)Marshal.SizeOf((object)lpBuffer); WindowsNative.GlobalMemoryStatusEx(ref lpBuffer); memoryLoad = lpBuffer.dwMemoryLoad; totalPhysicalMemory = lpBuffer.ullTotalPhys; availablePhysicalMemory = lpBuffer.ullAvailPhys; } public static long GetIdleMilliseconds() { WindowsNative.LASTINPUTINFO plii = default(WindowsNative.LASTINPUTINFO); plii.cbSize = (uint)Marshal.SizeOf((object)plii); WindowsNative.GetLastInputInfo(ref plii); uint tickCount = WindowsNative.GetTickCount(); if (plii.dwTime > tickCount) { return (long)tickCount + 4294967295L - plii.dwTime; } return tickCount - plii.dwTime; } public static CoreRect ToCoreRect(this WindowsNative.RECT rect) { return new CoreRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } public static IEnumerable GetAppDomains() { ICorRuntimeHost corRuntimeHost = (ICorRuntimeHost)new CorRuntimeHostClass(); corRuntimeHost.EnumDomains(out var enumHandle); try { while (true) { corRuntimeHost.NextDomain(enumHandle, out var pAppDomain); if (pAppDomain != null) { yield return (AppDomain)pAppDomain; continue; } break; } } finally { corRuntimeHost.CloseEnum(enumHandle); } } public unsafe static List GetNullDelimitedStrings(IntPtr address) { char* ptr = (char*)(void*)address; List list = new List(); while (true) { string text = new string(ptr); if (string.IsNullOrEmpty(text)) { break; } list.Add(text); ptr += text.Length + 1; } return list; } public static void TryUnblockFile(string filePath) { WindowsNative.DeleteFile(filePath + ":Zone.Identifier"); } public static void AssertWin32Result(this int result, params int[] allowedResults) { if (allowedResults == null || Array.IndexOf(allowedResults, result) == -1) { throw CreateWin32Exception(result); } } public static void AssertWin32ResultZero(this int result) { result.AssertWin32Result(default(int)); } public static void AssertWin32ResultZero(this uint result) { ((int)result).AssertWin32Result(default(int)); } public static void AssertComResultZero(this uint result) { if (result != 0) { throw new COMException(null, (int)result); } } public static Rectangle ToRectangle(this CoreRect coreRect) { return new Rectangle(coreRect.X, coreRect.Y, coreRect.Width, coreRect.Height); } public static CoreRect ToCoreRect(this Rectangle rectangle) { return new CoreRect(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } public static Point ToPoint(this CorePoint corePoint) { return new Point(corePoint.X, corePoint.Y); } public static CorePoint ToCorePoint(this Point point) { return new CorePoint(point.X, point.Y); } public static Size ToSize(this CoreSize coreSize) { return new Size(coreSize.Width, coreSize.Height); } public static CoreSize ToCoreSize(this Size size) { return new CoreSize(size.Width, size.Height); } public unsafe static Version GetTrueOSVersion() { WindowsNative.OSVERSIONINFOEX oSVERSIONINFOEX = default(WindowsNative.OSVERSIONINFOEX); oSVERSIONINFOEX.dwOSVersionInfoSize = sizeof(WindowsNative.OSVERSIONINFOEX); WindowsNative.RtlGetVersion(&oSVERSIONINFOEX); return new Version(oSVERSIONINFOEX.dwMajorVersion, oSVERSIONINFOEX.dwMinorVersion, oSVERSIONINFOEX.dwBuildNumber, 0); } public static IDisposable TryDisableFileSystemRedirectionTemporarily() { if (GetTrueOSVersion() < new Version(6, 0)) { return null; } IntPtr handle = default(IntPtr); if (!WindowsNative.Wow64DisableWow64FsRedirection(ref handle)) { return null; } return new ProcDisposable(delegate { WindowsNative.Wow64RevertWow64FsRedirection(handle); }); } public static string[]? GetPathDirectoryPaths() { return Environment.GetEnvironmentVariable("PATH").SafePipe((string it) => it.Split(new char[1] { ';' }).WhereNotNullOrWhitespace().ToArray()); } public static string? GetFullExecutablePath(string executableFileName) { return (from it in GetPathDirectoryPaths().SafeEnumerate().Prepend(AppDomain.CurrentDomain.BaseDirectory) select Path.Combine(it, executableFileName) into it where File.Exists(it) select it).FirstOrDefault(); } public static Rectangle GetWindowScreenWorkingArea(IntPtr windowHandle) { IntPtr hMonitor = WindowsNative.MonitorFromWindow(windowHandle, 2); WindowsNative.MONITORINFO lpmi = new WindowsNative.MONITORINFO { cbSize = Marshal.SizeOf(typeof(WindowsNative.MONITORINFO)) }; WindowsNative.GetMonitorInfo(hMonitor, ref lpmi).AssertTrueOrThrowLastWin32Error("WindowsNative.GetMonitorInfo(monitorHandle, ref monitorInfo)"); return lpmi.rcWork.ToCoreRect().ToRectangle(); } public static CoreRect GetWindowRectangle(IntPtr windowHandle) { WindowsNative.RECT lpRect = default(WindowsNative.RECT); WindowsNative.GetWindowRect(windowHandle, ref lpRect); return lpRect.ToCoreRect(); } public static CoreRect GetClientRectangle(IntPtr windowHandle) { WindowsNative.RECT lpRect = default(WindowsNative.RECT); WindowsNative.GetClientRect(windowHandle, ref lpRect); return lpRect.ToCoreRect(); } public static bool GetWindowInfo(IntPtr windowHandle, out WindowsNative.WINDOWINFO windowInfo) { windowInfo = new WindowsNative.WINDOWINFO { cbSize = WindowsNative.WindowInfoSize }; return WindowsNative.GetWindowInfo(windowHandle, ref windowInfo); } public static string? GetWindowText(IntPtr windowHandle) { StringBuilder stringBuilder = new StringBuilder(256); WindowsNative.GetWindowText(windowHandle, stringBuilder, stringBuilder.Capacity); if (stringBuilder.Length == 0) { return null; } return stringBuilder.ToString(); } public static void CreateFile(string path, FileSecurity? fileSecurity = null) { File.Create(path, 1, FileOptions.None, fileSecurity).Dispose(); } public static void MoveFile(string sourcePath, string destinationPath, bool overwrite = false, bool allowCopy = true) { if (!WindowsNative.MoveFileEx(sourcePath, destinationPath, ((WindowsNative.MOVEFILE)0).EnsureFlags(WindowsNative.MOVEFILE.REPLACE_EXISTING, overwrite).EnsureFlags(WindowsNative.MOVEFILE.COPY_ALLOWED, allowCopy))) { ThrowLastError(); } } public static IList GetFrameworkTraceSources() { List list = typeof(TraceSource).GetField("tracesources", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null).To>(); lock (list) { return list.Select((WeakReference it) => it.Target).OfType().ToList(); } } public static Bitmap? TryGetBitmap(this ResourceManagerEx resourceManager, string name) { return resourceManager.GetObject(name).TrySafePipe((Func)delegate(object resource) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown return new Bitmap((Stream)new MemoryStream((byte[])resource)); }, (Bitmap?)null); } public static Bitmap? TryGetBitmap(this ResourceManagerEx resourceManager, string name, Size size) { return resourceManager.TryGetBitmap(name).TrySafePipe((Bitmap originalBitmap) => ((Image)(object)originalBitmap).GetResizedBitmap(size)); } public static Bitmap? GetResizedBitmap(this Image originalImage, Size size) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown Bitmap val = new Bitmap(size.Width, size.Height); Graphics val2 = Graphics.FromImage((Image)(object)val); try { val2.InterpolationMode = (InterpolationMode)7; val2.DrawImage(originalImage, new Rectangle(0, 0, size.Width, size.Height)); return val; } finally { ((IDisposable)val2)?.Dispose(); } } public static void SubscribeToLogApplicationException() { Application.ThreadException += delegate(object o, ThreadExceptionEventArgs e) { Extensions.TryWriteExceptionToEventLog(e.Exception, 1); }; Application.SetUnhandledExceptionMode((UnhandledExceptionMode)1); } public static T WithChildren(this T control, params Control[] children) where T : Control { if (((Control)control).Parent != null || control is Form) { ((Control)control).Controls.AddRange(children); } else { EventHandler handler = null; handler = delegate { if (((Control)control).Parent != null) { ((Control)control).Controls.AddRange(children); ((Control)control).ParentChanged -= handler; } }; ((Control)control).ParentChanged += handler; } return control; } public static ManagementObject DemandSingleWmiObject(string wmiClassName, string? condition = null) { return GetSingleWmiObject(wmiClassName, condition).AssertNonNull("Single WMI object not found: " + wmiClassName); } public static ManagementObject? GetSingleWmiObject(string wmiClassName, string? condition = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ManagementObjectSearcher val = new ManagementObjectSearcher((ObjectQuery)new SelectQuery(wmiClassName, condition)); try { return val.GetSingleWmiObject(); } finally { ((IDisposable)val)?.Dispose(); } } public static ManagementObject? GetSingleWmiObject(this ManagementObjectSearcher @this) { ManagementObjectCollection val = @this.Get(); try { List source = ((IEnumerable?)val).OfType().ToList(); try { return source.FirstOrDefault(); } finally { source.Skip(1).ForEach2(delegate(ManagementObject _) { _.Dispose(); }); } } finally { ((IDisposable)val)?.Dispose(); } } public static LocalAdminPresentStatus HasLocalAdministrators() { try { return GetGroupMembers(GetAdministratorsGroupName()).Where(delegate(ManagementObject user) { string text = ((ManagementBaseObject)user)["SID"].ToString(); bool flag = (bool)((ManagementBaseObject)user)["Disabled"]; string text2 = ((ManagementBaseObject)user)["Name"].ToString(); Match match = Regex.Match(ApplicationSettings.Instance.CredentialProviderUserNameFormat, "^(.*?)\\{"); if (match.Success && text2.StartsWith(match.Groups[1].Value)) { return false; } return !text.EndsWith("-500") && !flag; }).Any() ? LocalAdminPresentStatus.Present : LocalAdminPresentStatus.NotPresent; } catch (Exception ex) { TypeTrace.TraceException(ex); return LocalAdminPresentStatus.Unknown; } } private static string GetAdministratorsGroupName() { ManagementObject val = DemandSingleWmiObject("Win32_Group", "LocalAccount = True AND SID = 'S-1-5-32-544'"); try { return ((ManagementBaseObject)val)["Name"].ToString(); } finally { ((IDisposable)val)?.Dispose(); } } private static IEnumerable GetGroupMembers(string groupName) { string text = "SELECT * FROM Win32_GroupUser WHERE GroupComponent=\"Win32_Group.Domain='" + Environment.MachineName + "',Name='" + groupName + "'\""; ManagementObjectSearcher searcher = new ManagementObjectSearcher(text); try { ManagementObjectCollection results = searcher.Get(); try { ManagementObjectEnumerator enumerator = results.GetEnumerator(); try { while (enumerator.MoveNext()) { string text2 = enumerator.Current["PartComponent"].ToString().Split(new char[1] { '=' })[2].Trim(new char[1] { '"' }); string text3 = "SELECT * FROM Win32_UserAccount WHERE Name='" + text2 + "' AND LocalAccount=True"; ManagementObjectSearcher userSearcher = new ManagementObjectSearcher(text3); try { ManagementObjectCollection userResults = userSearcher.Get(); try { ManagementObjectEnumerator enumerator2 = userResults.GetEnumerator(); try { while (enumerator2.MoveNext()) { ManagementBaseObject current = enumerator2.Current; yield return (ManagementObject)current; } } finally { ((IDisposable)enumerator2)?.Dispose(); } } finally { ((IDisposable)userResults)?.Dispose(); } } finally { ((IDisposable)userSearcher)?.Dispose(); } } } finally { ((IDisposable)enumerator)?.Dispose(); } } finally { ((IDisposable)results)?.Dispose(); } } finally { ((IDisposable)searcher)?.Dispose(); } } public static Point GetMessageMouseScreenLocation(IntPtr lParam) { try { return new Point((short)(int)lParam, (short)((int)lParam >>> 16)); } catch (OverflowException) { return Point.Empty; } } public static Rectangle GetScreenBounds(this Control control) { return control.RectangleToScreen(new Rectangle(Point.Empty, control.Size)); } public static byte[] CredProtect(string s) { string text = s + "\0"; int pcchMaxChars = 0; WindowsNative.CredProtect(fAsSelf: false, text, text.Length, (IntPtr)0, ref pcchMaxChars, out var ProtectionType); byte[] array = new byte[pcchMaxChars * Marshal.SystemDefaultCharSize]; IntPtr address; using (array.Fixed(out address)) { WindowsNative.CredProtect(fAsSelf: false, text, text.Length, address, ref pcchMaxChars, out ProtectionType); return array; } } public static byte[] CredPackAuthenticationBuffer64(string domain, string userName, string password) { byte[][] array = new byte[3][] { Encoding.Unicode.GetBytes(domain + "\0"), Encoding.Unicode.GetBytes(userName + "\0"), CredProtect(password) }; MemoryStream memoryStream = new MemoryStream(); BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(2u); binaryWriter.Write(0u); int num = 64; byte[][] array2 = array; foreach (byte[] array3 in array2) { binaryWriter.Write((ushort)(array3.Length - 2)); binaryWriter.Write((ushort)array3.Length); binaryWriter.Write(0u); binaryWriter.Write((ulong)num); num += array3.Length; } binaryWriter.Write(0uL); array2 = array; foreach (byte[] buffer in array2) { binaryWriter.Write(buffer); } return memoryStream.ToArray(); } public static (string? ExecutablePath, string? CommandLine, uint ParentProcessID) TryGetProcessInfo(int processID) { ManagementObject singleWmiObject = GetSingleWmiObject("Win32_Process", $"ProcessId={processID}"); try { return singleWmiObject.SafePipe((ManagementObject it) => (((string)((ManagementBaseObject)it)["ExecutablePath"])?.Trim(new char[1] { '"' }), (string)((ManagementBaseObject)it)["CommandLine"], (uint)((ManagementBaseObject)it)["ParentProcessId"])); } finally { ((IDisposable)singleWmiObject)?.Dispose(); } } public static CoreVersion? TryGetFileProductVersion(string filePath) { return filePath.TryPipe((string it) => FileVersionInfo.GetVersionInfo(it).ProductVersion)?.Pipe(DataObject.GetVersion); } public static uint? TryTerminateProcess(string processExecutablePath) { ManagementObject singleWmiObject = GetSingleWmiObject("Win32_Process", "ExecutablePath='" + processExecutablePath.Pipe((string it) => it.Replace("\\", "\\\\")) + "'"); try { return (uint?)((singleWmiObject != null) ? singleWmiObject.InvokeMethod("Terminate", (object[])null) : null); } finally { ((IDisposable)singleWmiObject)?.Dispose(); } } public static IEnumerable GetChildWindowHandles(IntPtr parentWindowHandle) { IntPtr childWindowHandle = WindowsNative.GetWindow(parentWindowHandle, WindowsNative.GW.CHILD); while (childWindowHandle != (IntPtr)0) { yield return childWindowHandle; childWindowHandle = WindowsNative.GetWindow(childWindowHandle, WindowsNative.GW.HWNDNEXT); } } public static IList GetWindowHandles() { return ToList(delegate(Func func) { WindowsNative.EnumWindows((IntPtr item, IntPtr _) => func(item), (IntPtr)0); }); } public static IList GetDescendentWindowHandles(IntPtr parentWindowHandle) { return ToList(delegate(Func func) { WindowsNative.EnumChildWindows(parentWindowHandle, (IntPtr item, IntPtr _) => func(item), (IntPtr)0); }); } public static IList GetDesktopWindowHandles(IntPtr desktopHandle) { return ToList(delegate(Func func) { WindowsNative.EnumDesktopWindows(desktopHandle, (IntPtr item, IntPtr _) => func(item), (IntPtr)0); }); } public static IList GetDesktopNames(IntPtr windowStationHandle) { return ToList(delegate(Func func) { WindowsNative.EnumDesktops(windowStationHandle, (string item, IntPtr _) => func(item), (IntPtr)0); }); } public static IList GetWindowStationNames() { return ToList(delegate(Func func) { WindowsNative.EnumWindowStations((string item, IntPtr _) => func(item), (IntPtr)0); }); } private static IList ToList(Proc> enumerateProc) { List items = new List(); enumerateProc(delegate(T item) { items.Add(item); return true; }); return items; } public static void PerformWithFileSystemTransaction(Proc proc) { IntPtr intPtr = default(IntPtr); try { intPtr = WindowsNative.CreateTransaction(IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, null); proc(intPtr); WindowsNative.CommitTransaction(intPtr); } catch { if (intPtr != IntPtr.Zero) { WindowsNative.RollbackTransaction(intPtr); } throw; } } public static void CreateSymbolicLink(string path, string targetPath) { WindowsNative.CreateSymbolicLink(path, targetPath, 0); } public unsafe static string? TryGetSymbolicLinkTargetPath(string path) { using SafeFileHandle hDevice = WindowsNative.CreateFile(path, 8u, 7u, null, 3u, 35651584u, IntPtr.Zero); int num = 0; WindowsNative.REPARSE_DATA_BUFFER rEPARSE_DATA_BUFFER = default(WindowsNative.REPARSE_DATA_BUFFER); bool flag = WindowsNative.DeviceIoControl(hDevice, 589992, null, 0, &rEPARSE_DATA_BUFFER, sizeof(WindowsNative.REPARSE_DATA_BUFFER), &num, IntPtr.Zero); return (flag && rEPARSE_DATA_BUFFER.ReparseTag == WindowsNative.IO_REPARSE_TAG.SYMLINK) ? Marshal.PtrToStringUni((IntPtr)(rEPARSE_DATA_BUFFER.Union.SymbolicLinkReparseBuffer.PathBuffer + (int)rEPARSE_DATA_BUFFER.Union.SymbolicLinkReparseBuffer.PrintNameOffset), rEPARSE_DATA_BUFFER.Union.SymbolicLinkReparseBuffer.PrintNameLength / 2) : ((flag && rEPARSE_DATA_BUFFER.ReparseTag == WindowsNative.IO_REPARSE_TAG.MOUNT_POINT && rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.PrintNameLength > 0) ? Marshal.PtrToStringUni((IntPtr)(rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.PathBuffer + (int)rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.PrintNameOffset), rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.PrintNameLength / 2) : ((flag && rEPARSE_DATA_BUFFER.ReparseTag == WindowsNative.IO_REPARSE_TAG.MOUNT_POINT) ? Marshal.PtrToStringUni((IntPtr)(rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.PathBuffer + (int)rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.SubstituteNameOffset), rEPARSE_DATA_BUFFER.Union.MountPointReparseBuffer.SubstituteNameLength / 2).TrimStart(new char[2] { '\\', '?' }) : null)); } }