C# 调用API,实现注销远程登录本机的用户

转载 2007年09月23日 10:19:00
<iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-9043283529440151&amp;dt=1190513439683&amp;lmt=1190513439&amp;format=468x60_as&amp;output=html&amp;correlator=1190513439673&amp;channel=4153268400&amp;url=http%3A%2F%2Fwww.vs2005.com%2FCode%2F396%2F1%2Fdefault.aspx&amp;color_bg=FFFFFF&amp;color_text=000000&amp;color_link=000000&amp;color_url=000000&amp;color_border=FFFFFF&amp;ad_type=text_image&amp;cc=100&amp;ga_vid=1748915312.1190512828&amp;ga_sid=1190512828&amp;ga_hid=1107433074&amp;ga_fc=true&amp;flash=9&amp;u_h=768&amp;u_w=1024&amp;u_ah=738&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_java=true" frameborder="0" width="468" scrolling="no" height="60" allowtransparency="allowtransparency"></iframe>
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();

                        bool bsuccess = TSControl.WTSQuerySessionInformation(IntPtr.Zero, pSessionInfo[i].SessionID, TSControl.WTSInfoClass.WTSUserName, out sb, 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();
        }
    }
}
 
举报

相关文章推荐

MySQL:免远程登录服务器本机访问服务器上的数据库或者服务器之间的数据库远程访问。

1.      第一步 , 在服务器端登陆进mysql,使用命令:mysql –u root –p输入密码即可登录 2.      使用命令:grant all privil...

win2003实现单用户远程登录

一般情况下,我们会觉得xp只能登录一个远程用户很不爽,每次一个用户登录就会把另一个用户踢掉,所以需要多用户都能使用远程桌面的情况下,使用windows2003是最简单的方法了。    但反过来呢,如果...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

实现Windows Server 2003多用户远程登录

实现Windows Server 2003多用户远程登录   Windows Server 2003默认情况下允许远程终端连接的数量是2个用户,我们可以根据需要适当增加远程连接同时在线的用户数。 ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)