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

转载 2007年09月25日 12:30:00
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();
        }
    }
}
 

C#调用Windows API实现自动登录

设计初衷:  公司为了便于网络管理,使用了IEEE 802.1X的网络访问控制,这样每次开机需要输入两次登录密码,于是我就研究了一下用C#来帮我输入第二此登录的密码  设计思想:  主要是通过调...
  • chenyulancn
  • chenyulancn
  • 2016年06月04日 17:02
  • 1108

PHP与MYSQL实现用户登录注销

因为最近才学习php与mysql,为了写留言板的注册,登录与注销功能,接触到php的session会话机制,想要记录下来。Session: 代表服务器与浏览器的一次会话过程(其本来的含义是指有始有终的...
  • xyj96
  • xyj96
  • 2016年05月14日 11:07
  • 1280

用户登录及用户注销

登录界面; String path = request.getContextPath(); String basePath = request.getScheme() + "://" +...
  • pangqiandou
  • pangqiandou
  • 2016年10月01日 11:02
  • 610

Linux学习(CentOS-7)---登录和注销Linux系统

Linux是一个多用户的操作系统,用户要使用该系统,首先必须登录系统,使用完系统后,必须退出系统。本章主要讨论登录和退出系统的方法。用户登录系统时,为了使系统能够识别自己,必须输入用户名和密码,经系统...
  • huangxiang360729
  • huangxiang360729
  • 2016年09月24日 13:46
  • 6876

【JSP开发】有关session的登录注销的一个小例子

下面是一个session的应用的小例子,是用来注销登录的 登陆界面的代码: login.html: login.html -...
  • u013517797
  • u013517797
  • 2015年02月03日 15:42
  • 7134

c#调用api控制windows关机示例

本文介绍了c#控制windows关机、重启、注销的二种方法,分为调用windows自带的shutdown.exe关机和调用API关机的方法 方法一:调用windows自带的shutd...
  • u012993732
  • u012993732
  • 2014年11月06日 09:08
  • 286

Shiro 整合SpringMVC 并且实现权限管理,登录和注销

Apache Shiro是Java的一个安全框架。目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可能没有Spring Security做的功能强大...
  • zhenwodefengcaii
  • zhenwodefengcaii
  • 2017年01月17日 21:52
  • 898

利用session完成用户登录与注销

Cookie:cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。 当用户使用浏览器再去访问服务器中的 web资源时,就会带着各自的数据区,这样,web资源处理...
  • u010143291
  • u010143291
  • 2016年06月06日 18:46
  • 6588

使用命令远程注销服务器

有时我们远程登录的服务器人数满或卡住,导致我们无法正常使用或连接远程服务器,怎么办?相信运维同事可能遇到这种问题最多,但有时研发同事也会遇到,看到他们在那“干等待,我的那个急呀”,接下来告诉大家一个方...
  • hexieshangwang
  • hexieshangwang
  • 2015年08月11日 10:04
  • 421788

ssh安全远程登录的身份认证原理

概述SSH是Secure Shell(安全外壳)的简称。用户通过一个不能保证安全的网络环境远程登录到设备时,SSH可以利用加密和强大的认证功能提供安全保障,保护设备不受诸如IP地址欺诈、明文密码截取等...
  • brandohero
  • brandohero
  • 2013年01月07日 02:07
  • 1762
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:C# 调用API,实现注销远程登录本机的用户
举报原因:
原因补充:

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