public static bool UnregisterNotification(IntPtr hWnd) { logger.Debug("UnregisterNotification()"); bool success = false; try { success = WtsApi32.WTSUnRegisterSessionNotification(hWnd); if (!success) { var lastError = Marshal.GetLastWin32Error(); logger.Error("WTSUnRegisterSessionNotification() " + lastError); } } catch (Exception ex) { logger.Error(ex); } return(success); }
public static bool RegisterNotification(IntPtr hWnd) { logger.Debug("RegisterNotification() " + hWnd); var result = false; try { result = WtsApi32.WTSRegisterSessionNotification(hWnd, WtsApi32.NOTIFY_FOR_THIS_SESSION); if (!result) { var code = Marshal.GetLastWin32Error(); logger.Error("WTSRegisterSessionNotification() " + code); } } catch (Exception ex) { logger.Error(ex); } return(result); }
public static WtsApi32.WTS_SESSION_INFO[] GetWTSSessions(IntPtr server) { List <WtsApi32.WTS_SESSION_INFO> ret = new List <WtsApi32.WTS_SESSION_INFO>(); int structSize = Marshal.SizeOf(typeof(WtsApi32.WTS_SESSION_INFO)); IntPtr ppSessionInfo; uint count; if (!WtsApi32.WTSEnumerateSessions( server, 0, 1, out ppSessionInfo, out count)) { Win32Error.Set("WTSEnumerateSessions"); throw new Exception(Win32Error.GetFullErrMsg()); } IntPtr element = ppSessionInfo; for (uint i = 0; i < count; ++i) { ret.Add( (WtsApi32.WTS_SESSION_INFO)Marshal.PtrToStructure( element, typeof(WtsApi32.WTS_SESSION_INFO) ) ); element = (IntPtr)((Int64)element + structSize); } WtsApi32.WTSFreeMemory(ppSessionInfo); return(ret.ToArray()); }
private static bool InformInstallerInitiator( string installStatus, uint timeout = 0) // Informs the user who ran Setup.exe about the overall // success or failure of the 'InstallAgent' // Returns 'true' if the user was successfully informed; // 'false' otherwise { string text = Branding.GetString("BRANDING_managementName"); if (installStatus.Equals("Installed")) { text += " installed successfully"; } else if (installStatus.Equals("Failed")) { text += " failed to install"; } else { throw new Exception( "InstallStatus: \'" + installStatus + "\' not supported" ); } string caption = Branding.GetString("BRANDING_manufacturer") + " " + Branding.GetString("BRANDING_hypervisorProduct") + " " + Branding.GetString("BRANDING_managementName") + " " + "Setup"; string sid = GetInstallerInitiatorSid(); WtsApi32.ID resp; WtsApi32.WTS_SESSION_INFO[] sessions = Helpers.GetWTSSessions( WtsApi32.WTS_CURRENT_SERVER_HANDLE ); foreach (WtsApi32.WTS_SESSION_INFO si in sessions) { if (si.State == WtsApi32.WTS_CONNECTSTATE_CLASS.WTSActive && sid.Equals(Helpers.GetUserSidFromSessionId(si.SessionID))) { if (!WtsApi32.WTSSendMessage( WtsApi32.WTS_CURRENT_SERVER_HANDLE, si.SessionID, caption, (uint)caption.Length * sizeof(Char), text, (uint)text.Length * sizeof(Char), WtsApi32.MB.OK | WtsApi32.MB.ICONINFORMATION, timeout, out resp, false)) { Win32Error.Set("WTSSendMessage"); throw new Exception(Win32Error.GetFullErrMsg()); } return(true); } } return(false); }
public static string GetUserSidFromSessionId(UInt32 sessionId) // Gets the unique Security Identifier (SID) // of the User logged on to 'sessionId' { IntPtr token = (IntPtr)0; IntPtr tokenInf = IntPtr.Zero; uint tokenInfLen = 0; IntPtr szSid = IntPtr.Zero; string sid; try { AcquireSystemPrivilege(AdvApi32.SE_TCB_NAME); Trace.WriteLine("Using session id " + sessionId.ToString()); if (!WtsApi32.WTSQueryUserToken(sessionId, out token)) { Win32Error.Set("WTSQueryUserToken"); throw new Exception(Win32Error.GetFullErrMsg()); } // Get tokenInfLen AdvApi32.GetTokenInformation( token, AdvApi32.TOKEN_INFORMATION_CLASS.TokenUser, tokenInf, tokenInfLen, out tokenInfLen ); Win32Error.Set("GetTokenInformation"); if (Win32Error.GetErrorNo() != WinError.ERROR_INSUFFICIENT_BUFFER) { throw new Exception(Win32Error.GetFullErrMsg()); } tokenInf = Marshal.AllocHGlobal((int)tokenInfLen); if (!AdvApi32.GetTokenInformation( token, AdvApi32.TOKEN_INFORMATION_CLASS.TokenUser, tokenInf, tokenInfLen, out tokenInfLen)) { Win32Error.Set("GetTokenInformation"); throw new Exception(Win32Error.GetFullErrMsg()); } AdvApi32.TOKEN_USER tokenUser = (AdvApi32.TOKEN_USER)Marshal.PtrToStructure( tokenInf, typeof(AdvApi32.TOKEN_USER) ); if (!AdvApi32.ConvertSidToStringSid( tokenUser.User.Sid, out szSid)) { Win32Error.Set("ConvertSidToStringSid"); throw new Exception(Win32Error.GetFullErrMsg()); } sid = Marshal.PtrToStringAuto(szSid); return(sid); } finally { if (szSid != IntPtr.Zero) { Kernel32.LocalFree(szSid); } if (tokenInf != IntPtr.Zero) { Marshal.FreeHGlobal(tokenInf); } if (token != IntPtr.Zero) { Kernel32.CloseHandle(token); } } }
private static bool InformInstallerInitiator(uint timeout = 0) // Informs the user who ran Setup.exe about the overall // success or failure of the 'InstallAgent' // Returns 'true' if the user was successfully informed; // 'false' otherwise { string text = Branding.GetString("BRANDING_managementName"); if (installStatus == InstallStatus.Installed) { text = text + " " + Branding.GetString("BRANDING_installSuccess"); } else if (installStatus == InstallStatus.Failed) { text = text + " " + Branding.GetString("BRANDING_installFailed"); } else { throw new Exception( "InstallStatus: \'" + installStatus + "\' " + Branding.GetString("BRANDING_notSupport") ); } string caption = Branding.GetString("BRANDING_manufacturer") + " " + Branding.GetString("BRANDING_hypervisorProduct") + " " + Branding.GetString("BRANDING_managementName") + " " + Branding.GetString("BRANDING_setupString"); string sid = GetInstallerInitiatorSid(); WtsApi32.ID resp; WtsApi32.WTS_SESSION_INFO[] sessions = Helpers.GetWTSSessions( WtsApi32.WTS_CURRENT_SERVER_HANDLE ); foreach (WtsApi32.WTS_SESSION_INFO si in sessions) { bool equalSessionId; try { equalSessionId = (si.State == WtsApi32.WTS_CONNECTSTATE_CLASS.WTSActive && sid.Equals(Helpers.GetUserSidFromSessionId(si.SessionID))); } catch (Exception e) { Trace.WriteLine("Unknown user for session id " + si.SessionID.ToString() + " " + e.ToString()); continue; } if (equalSessionId) { if (!WtsApi32.WTSSendMessage( WtsApi32.WTS_CURRENT_SERVER_HANDLE, si.SessionID, caption, (uint)caption.Length * sizeof(Char), text, (uint)text.Length * sizeof(Char), WtsApi32.MB.OK | WtsApi32.MB.ICONINFORMATION, timeout, out resp, false)) { Win32Error.Set("WTSSendMessage"); throw new Exception(Win32Error.GetFullErrMsg()); } return(true); } } return(false); }
public void Connect() { mHandle = WtsApi32.WTSVirtualChannelOpen(IntPtr.Zero, -1, ChannelMessage.ChannelName); if (mHandle == IntPtr.Zero) { //Log("RDP Virtual channel Open Failed: " + new Win32Exception().Message); return; } try { byte[] buf = new byte[1024]; uint bytesRead; string text = ""; while (true) { if (WtsApi32.WTSVirtualChannelRead(mHandle, 0, buf, (uint)buf.Length, out bytesRead) != 0) { text = Encoding.Unicode.GetString(buf, 0, (int)bytesRead); } if (!string.IsNullOrEmpty(text)) { #region old /*string result = ""; * for (int i = 0; i < text.Length; i++) * { * if ((int)text[i] > 32 && (int)text[i] < 127) * { * result += text[i].ToString(); * } * else * { * result += string.Format("\\u{0:x4}", (int)text[i]); * } * } * * string tmpResult = new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace( * result, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));*/ /* //1、获取桌面窗口的句柄 * IntPtr desktopPtr = WinHelper.GetDesktopWindow(); * Write(desktopPtr.ToString() + ":" + GetHandleInfo(desktopPtr) + "\r\n"); * //2、获得一个子窗口(这通常是一个顶层窗口,当前活动的窗口) * IntPtr winPtr = WinHelper.GetWindow(desktopPtr, GetWindowCmd.GW_CHILD); * Write(winPtr.ToString() + ":" + GetHandleInfo(winPtr) + "\r\n"); * //3、循环取得桌面下的所有子窗口 * while (winPtr != IntPtr.Zero) * { * //4、继续获取下一个子窗口 * winPtr = WinHelper.GetWindow(winPtr, GetWindowCmd.GW_HWNDNEXT); * Write(winPtr.ToString() + ":" + GetHandleInfo(winPtr) + "\r\n"); * if (GetHandleInfo(winPtr).Contains("记事本")) * { * break; * } * }*/ #endregion if (text.Contains("使用服务端输入法")) { //解除键盘监控钩子 btnUninstallHook_Click(this, null); } else if (text.Contains("使用客户端输入法")) { btnInstallHook_Click(this, null); } else { WinHelper.SetForegroundWindow(WinHelper.foreGroundHandle); //WinHelper.SendMessage(WinHelper.foreGroundHandle, 11, IntPtr.Zero, IntPtr.Zero); //WinHelper.SendMessage(WinHelper.foreGroundHandle, 11, (IntPtr)(-1), IntPtr.Zero); WinHelper.SendText(text, WinHelper.foreGroundHandle); } } } } catch (Win32Exception ex) { //Log("RDP Virtual channel Query Failed: " + ex.Message); return; } }
public static void StartAsActiveUser(this Process process) { // Sanity check. if (process.StartInfo == null) { throw new InvalidOperationException("The StartInfo property must be defined"); } if (string.IsNullOrEmpty(process.StartInfo.FileName)) { throw new InvalidOperationException("The StartInfo.FileName property must be defined"); } // Retrieve the active session ID and its related user token. var sessionId = Kernel32.WTSGetActiveConsoleSessionId(); var userTokenPtr = new IntPtr(); if (!WtsApi32.WTSQueryUserToken(sessionId, out userTokenPtr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Duplicate the user token so that it can be used to create a process. var duplicateUserTokenPtr = new IntPtr(); if (!AdvApi32.DuplicateTokenEx(userTokenPtr, AdvApi32.MAXIMUM_ALLOWED, null, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out duplicateUserTokenPtr)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Create an environment block for the interactive process. var environmentPtr = new IntPtr(); if (!UserEnv.CreateEnvironmentBlock(out environmentPtr, duplicateUserTokenPtr, false)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Create the process under the target user’s context. var processFlags = CREATE_PROCESS_FLAGS.NORMAL_PRIORITY_CLASS | CREATE_PROCESS_FLAGS.CREATE_NEW_CONSOLE | CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT; var processInfo = new PROCESS_INFORMATION(); var startupInfo = new STARTUPINFO(); startupInfo.cb = Marshal.SizeOf(startupInfo); if (!AdvApi32.CreateProcessAsUser ( duplicateUserTokenPtr, process.StartInfo.FileName, process.StartInfo.Arguments, null, null, false, processFlags, environmentPtr, null, ref startupInfo, out processInfo )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Free used resources. Kernel32.CloseHandle(processInfo.hProcess); Kernel32.CloseHandle(processInfo.hThread); if (userTokenPtr != null) { Kernel32.CloseHandle(userTokenPtr); } if (duplicateUserTokenPtr != null) { Kernel32.CloseHandle(duplicateUserTokenPtr); } if (environmentPtr != null) { UserEnv.DestroyEnvironmentBlock(environmentPtr); } }