public static IntPtr GetCurrentUserToken() { IntPtr primaryToken = IntPtr.Zero; IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; int dwSessionId = 0; IntPtr hUserToken = IntPtr.Zero; IntPtr hTokenDup = IntPtr.Zero; IntPtr pSessionInfo = IntPtr.Zero; int dwCount = 0; NativeMethods.WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref dwCount); Int32 dataSize = Marshal.SizeOf(typeof(NativeMethods.WTS_SESSION_INFO)); Int32 current = (int)pSessionInfo; for (int i = 0; i < dwCount; i++) { NativeMethods.WTS_SESSION_INFO si = (NativeMethods.WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(NativeMethods.WTS_SESSION_INFO)); if (NativeMethods.WTS_CONNECTSTATE_CLASS.WTSActive == si.State) { dwSessionId = si.SessionID; break; } current += dataSize; } NativeMethods.WTSFreeMemory(pSessionInfo); bool bRet = NativeMethods.WTSQueryUserToken(dwSessionId, out primaryToken); if (bRet == false) { return(IntPtr.Zero); } return(primaryToken); }
private void GetSessions() { IntPtr server = IntPtr.Zero; List <string> ret = new List <string>(); try { server = NativeMethods.WTSOpenServer("."); IntPtr ppSessionInfo = IntPtr.Zero; int count = 0; int retval = NativeMethods.WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count); int dataSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(NativeMethods.WTS_SESSION_INFO)); long current = (int)ppSessionInfo; if (retval != 0) { for (int i = 0; i < count; i++) { NativeMethods.WTS_SESSION_INFO si = (NativeMethods.WTS_SESSION_INFO)System.Runtime.InteropServices.Marshal.PtrToStructure((System.IntPtr)current, typeof(NativeMethods.WTS_SESSION_INFO)); current += dataSize; ret.Add(si.SessionID + " " + si.State + " " + si.pWinStationName); } NativeMethods.WTSFreeMemory(ppSessionInfo); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { try { NativeMethods.WTSCloseServer(server); } catch (Exception) { } } }