4

ユーザーのターミナルサーバーセッションから基になるクライアントPC名を取得する必要があります。

私はそれが住んでいることを知っていますが、HKEY_CURRENT_USER\Volatile Environment\CLIENTNAMEそれを取得する別の(できればネイティブの.net)方法はありますか?

4

2 に答える 2

14

このためのマネージAPIは表示されませんでした。この情報を取得するために私が見ることができる唯一のAPIベースの方法は、WMIまたはWindowsのネイティブターミナルサービスAPIを使用することです。

WTSQuerySessionInformationAPIを使用してクライアント名を返す例を次に示します。

namespace com.stackoverflow
{
    using System;
    using System.Runtime.InteropServices;

    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetTerminalServicesClientName());
        }

        /// <summary>
        /// Gets the name of the client system.
        /// </summary>
        internal static string GetTerminalServicesClientName()
        {
            IntPtr buffer = IntPtr.Zero;

            string clientName = null;
            int bytesReturned;

            bool success = NativeMethods.WTSQuerySessionInformation(
                NativeMethods.WTS_CURRENT_SERVER_HANDLE,
                NativeMethods.WTS_CURRENT_SESSION,
                NativeMethods.WTS_INFO_CLASS.WTSClientName,
                out buffer,
                out bytesReturned);

            if (success)
            {
                clientName = Marshal.PtrToStringUni(
                    buffer,
                    bytesReturned / 2 /* Because the DllImport uses CharSet.Unicode */
                    );
                NativeMethods.WTSFreeMemory(buffer);
            }

            return clientName;
        }
    }

    public static class NativeMethods
    {
        public static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
        public const int WTS_CURRENT_SESSION = -1;

        public enum WTS_INFO_CLASS
        {
            WTSClientName = 10
        }

        [DllImport("Wtsapi32.dll", CharSet = CharSet.Unicode)]
        public static extern bool WTSQuerySessionInformation(
            IntPtr hServer,
            Int32 sessionId,
            WTS_INFO_CLASS wtsInfoClass,
            out IntPtr ppBuffer,
            out Int32 pBytesReturned);

        /// <summary>
        /// The WTSFreeMemory function frees memory allocated by a Terminal
        /// Services function.
        /// </summary>
        /// <param name="memory">Pointer to the memory to free.</param>
        [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
        public static extern void WTSFreeMemory(IntPtr memory);
    }
}
于 2011-03-16T04:54:03.333 に答える
2

これらの回答を完了するために、Citrix Developer Network WebサイトでホストされているC#プロジェクトがあり、RDPサーバー上のセッションとそのIPアドレスを一覧表示するコードを提供しています。

ターミナルサービスAPIを使用してクライアントIPアドレスとクライアントホスト名を取得する方法

于 2011-10-18T08:05:18.207 に答える