Advertisement
Guest User

Untitled

a guest
Sep 12th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1.     static class TerminalClientName
  2.     {
  3.         /// <summary>
  4.         /// Gets the name of the client system.
  5.         /// </summary>
  6.         internal static string GetTerminalServicesClientName()
  7.         {
  8.             IntPtr buffer = IntPtr.Zero;
  9.  
  10.             string clientName = null;
  11.             int bytesReturned;
  12.  
  13.             bool success = NativeMethods.WTSQuerySessionInformation(
  14.                 NativeMethods.WTS_CURRENT_SERVER_HANDLE,
  15.                 NativeMethods.WTS_CURRENT_SESSION,
  16.                 NativeMethods.WTS_INFO_CLASS.WTSClientName,
  17.                 out buffer,
  18.                 out bytesReturned);
  19.  
  20.             if (success)
  21.             {
  22.                 clientName = Marshal.PtrToStringUni(
  23.                     buffer,
  24.                     bytesReturned / 2 /* Because the DllImport uses CharSet.Unicode */
  25.                     );
  26.                 NativeMethods.WTSFreeMemory(buffer);
  27.             }
  28.  
  29.             return clientName;
  30.         }
  31.     }
  32.  
  33.     public static class NativeMethods
  34.     {
  35.         public static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
  36.         public const int WTS_CURRENT_SESSION = -1;
  37.  
  38.         public enum WTS_INFO_CLASS
  39.         {
  40.             WTSClientName = 10
  41.         }
  42.  
  43.         [DllImport("Wtsapi32.dll", CharSet = CharSet.Unicode)]
  44.         public static extern bool WTSQuerySessionInformation(
  45.             IntPtr hServer,
  46.             Int32 sessionId,
  47.             WTS_INFO_CLASS wtsInfoClass,
  48.             out IntPtr ppBuffer,
  49.             out Int32 pBytesReturned);
  50.  
  51.         /// <summary>
  52.         /// The WTSFreeMemory function frees memory allocated by a Terminal
  53.         /// Services function.
  54.         /// </summary>
  55.         /// <param name="memory">Pointer to the memory to free.</param>
  56.         [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
  57.         public static extern void WTSFreeMemory(IntPtr memory);
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement