C# 調用API,實現登出遠程登入原生使用者 以及 遠程登入使用者獲得自己使用者名稱(轉+原);

來源:互聯網
上載者:User


 

這裡不單單是代碼,雖然代碼比較多,下面有用的地方我加了注釋和一些廢話。

 

using System;

using System.Management;

using System.Runtime;

using System.Runtime.InteropServices;
using System.Text;

namespace TSConsoleApplication
{
    /**/
    /// <summary>
    /// VS2005專業教程網收集整理,http://www.vs2005.com/
    /// </summary>
    public class TSControl
    {
        /**/
        /// <summary>
        /// Terminal Services API Functions,The WTSEnumerateSessions function retrieves a list of sessions on a specified terminal server,
        /// </summary>
        /// <param name="hServer">[in] Handle to a terminal server. Specify a handle opened by the WTSOpenServer function, or specify WTS_CURRENT_SERVER_HANDLE to indicate the terminal server on which your application is running</param>
        /// <param name="Reserved">Reserved; must be zero</param>
        /// <param name="Version">[in] Specifies the version of the enumeration request. Must be 1. </param>
        /// <param name="ppSessionInfo">[out] Pointer to a variable that receives a pointer to an array of WTS_SESSION_INFO structures. Each structure in the array contains information about a session on the specified terminal server. To free the returned buffer, call the WTSFreeMemory function.
        /// To be able to enumerate a session, you need to have the Query Information permission.</param>
        /// <param name="pCount">[out] Pointer to the variable that receives the number of WTS_SESSION_INFO structures returned in the ppSessionInfo buffer. </param>
        /// <returns>If the function succeeds, the return value is a nonzero value. If the function fails, the return value is zero</returns>
        [DllImport("wtsapi32", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool WTSEnumerateSessions(int hServer, int Reserved, int Version, ref long ppSessionInfo, ref int pCount);

        /**/
        /// <summary>
        /// Terminal Services API Functions,The WTSFreeMemory function frees memory allocated by a Terminal Services function.
        /// </summary>
        /// <param name="pMemory">[in] Pointer to the memory to free</param>
        [DllImport("wtsapi32.dll")]
        public static extern void WTSFreeMemory(System.IntPtr pMemory);

        /**/
        /// <summary>
        /// Terminal Services API Functions,The WTSLogoffSession function logs off a specified Terminal Services session.
        /// </summary>
        /// <param name="hServer">[in] Handle to a terminal server. Specify a handle opened by the WTSOpenServer function, or specify WTS_CURRENT_SERVER_HANDLE to indicate the terminal server on which your application is running. </param>
        /// <param name="SessionId">[in] A Terminal Services session identifier. To indicate the current session, specify WTS_CURRENT_SESSION. You can use the WTSEnumerateSessions function to retrieve the identifiers of all sessions on a specified terminal server.
        /// To be able to log off another user's session, you need to have the Reset permission </param>
        /// <param name="bWait">[in] Indicates whether the operation is synchronous.
        /// If bWait is TRUE, the function returns when the session is logged off.
        /// If bWait is FALSE, the function returns immediately.</param>
        /// <returns>If the function succeeds, the return value is a nonzero value.
        /// If the function fails, the return value is zero.</returns>
        [DllImport("wtsapi32.dll")]
        public static extern bool WTSLogoffSession(int hServer, long SessionId, bool bWait);
        [DllImport("Wtsapi32.dll")]
        public static extern bool WTSQuerySessionInformation(
            System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out StringBuilder ppBuffer, out int pBytesReturned);

        public enum WTSInfoClass
        {
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSOEMId,
            WTSSessionId,
            WTSUserName,
            WTSWinStationName,
            WTSDomainName,
            WTSConnectState,
            WTSClientBuildNumber,
            WTSClientName,
            WTSClientDirectory,
            WTSClientProductId,
            WTSClientHardwareId,
            WTSClientAddress,
            WTSClientDisplay,
            WTSClientProtocolType
        }

        /**/
        /// <summary>
        /// The WTS_CONNECTSTATE_CLASS enumeration type contains INT values that indicate the connection state of a Terminal Services session.
        /// </summary>
        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit,
        }

        /**/
        /// <summary>
        /// The WTS_SESSION_INFO structure contains information about a client session on a terminal server.
        /// if the WTS_SESSION_INFO.SessionID==0, it means that the SESSION is the local logon user's session.
        /// </summary>
        public struct WTS_SESSION_INFO
        {
            public int SessionID;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pWinStationName;
            public WTS_CONNECTSTATE_CLASS state;
        }

        /**/
        /// <summary>
        /// The SessionEnumeration function retrieves a list of WTS_SESSION_INFO on a current terminal server.
        /// </summary>
        /// <returns>a list of WTS_SESSION_INFO on a current terminal server</returns>
        public static WTS_SESSION_INFO[] SessionEnumeration()
        {
            //Set handle of terminal server as the current terminal server
            int hServer = 0;
            bool RetVal;
            long lpBuffer = 0;
            int Count = 0;
            long p;
            WTS_SESSION_INFO Session_Info = new WTS_SESSION_INFO();
            WTS_SESSION_INFO[] arrSessionInfo;
            RetVal = WTSEnumerateSessions(hServer, 0, 1, ref lpBuffer, ref Count);
            arrSessionInfo = new WTS_SESSION_INFO[0];
            if (RetVal)
            {
                arrSessionInfo = new WTS_SESSION_INFO[Count];
                int i;
                p = lpBuffer;
                for (i = 0; i < Count; i++)
                {
                    arrSessionInfo[i] = (WTS_SESSION_INFO)Marshal.PtrToStructure(new IntPtr(p), Session_Info.GetType());
                    p += Marshal.SizeOf(Session_Info.GetType());
                }
                WTSFreeMemory(new IntPtr(lpBuffer));
            }
            else
            {
                //Insert Error Reaction Here
            }
            return arrSessionInfo;
        }

        public TSControl()
        {
            //
            // TODO: 在此處添加建構函式邏輯
            //

        }
    }

    /**/
    /// <summary>
    /// Class1 的摘要說明。
    /// </summary>
    class Class1
    {
        /**/
        /// <summary>
        /// 應用程式的主進入點。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: 在此處添加代碼以啟動應用程式
            //
            TSControl.WTS_SESSION_INFO[] pSessionInfo = TSControl.SessionEnumeration();

            for (int i = 0; i < pSessionInfo.Length; i++)
            {
                if (pSessionInfo[i].SessionID != 0)
                {
                    try
                    {
                        int count = 0;
                        IntPtr buffer = IntPtr.Zero;
                        StringBuilder sb = new StringBuilder();

                       
StringBuilder sa = new StringBuilder();

                        //上面的種種代碼就不解釋了其實重點就是這句話,WTSQuerySessionInformation函數

                        // 函數裡參數 我知道的做一下介紹,IntPtr.Zero 這個不明白 還請大哥們告訴。

                        //pSessionInfo[i]是 正在遠程登入的使用者資訊(視乎也包括自己)。SessionID是這個使用者的ID。。。

                        //函數會通過這個ID 知道你要得到哪個使用者的資訊。 之後的TSControl.WTSInfoClass.WTSUserName呢就是你想要的到的哪種資訊。 比如他這裡是,WTSUserName 是要得到登入的名字。這個枚舉裡面還有很多,比如說ip地址啦,使用者電腦名等等。

                        //sb是。。。。傳出的參數了。你要的得到的結果要從sb裡面拿。。。


                        bool bsuccess = TSControl.WTSQuerySessionInformation(IntPtr.Zero, pSessionInfo[i].SessionID, TSControl.WTSInfoClass.WTSUserName, out sb, out count);

 

                        //這句話呢是,遠程登入的使用者,可以得到自己的電腦名,似乎這個功能沒用,但是我做的一個項目確實用到了。不同的電腦通過遠程登入,運行同樣的程式,程式要判斷不同的電腦要展現不同的畫面。

                        //這裡唯一的區別就是,第二個參數 變成了-1 ,這個-1應該是標識自己的意思。這樣遠程登入的使用者會找到自己的資訊。ip地址或者使用者名稱等等。

                        bool bsuccess = TSControl.WTSQuerySessionInformation(IntPtr.Zero, -1, TSControl.WTSInfoClass.ClientName, out sa, out count);

 


                        if (bsuccess)

                        {
                            //如果使用者名稱為Administrator,則登出它。您可以通過改變 Administrator登出其它的使用者
                            if (sb.ToString().Trim() == "Administrator")

                            {
                                while (TSControl.WTSLogoffSession(0, pSessionInfo[i].SessionID, true))

                                {

                                    System.Threading.Thread.Sleep(3000);

                                }

                            }

                        }

                    }
                    catch (Exception ex)

                    {

                        Console.WriteLine(ex.Message);

                    }

                }

            }

            Console.ReadLine();

        }

    }


}

 

 

其實項目中用到了,能多學一些技術是好事,感謝http://blog.csdn.net/nbc_prc/archive/2007/10/17/1829072.aspx提供的源碼。  希望可以幫到需要的人。

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.