简体   繁体   English

如何仅终止本地计​​算机的远程桌面会话

[英]How to kill remote desktop session for local computer only

I'm using the following code to kill a remote desktop session and the application running in it.我正在使用以下代码来终止远程桌面会话和在其中运行的应用程序。 It works fine, the only problem is that it kills the specified application for all users.它工作正常,唯一的问题是它会杀死所有用户的指定应用程序。

How do I keep this to just the local machine running a session?我如何将它保留在运行会话的本地机器上?

We have multiple users logging in and running this application from a server on their local machines.我们有多个用户从他们本地机器上的服务器登录并运行这个应用程序。 Most are running using work resources, but some use remote desktop.大多数使用工作资源运行,但有些使用远程桌面。

No matter how they are logged in when I run my code all users loose their sessions.无论我运行我的代码时他们如何登录,所有用户都失去了他们的会话。

private void btnCloseSession_Click(object sender, EventArgs e)
    {
        if (!runningExclusiveProcess)
        {
            runningExclusiveProcess = true;
            btnCloseSession.Enabled = false;
                //check and close Labware if running
                if (chkCloseLabware.Checked == true) 
            {
                if (chkExit.Checked == true)
                {
                    KillLabWare();
                    Close();
                }
                else
                {
                    KillLabWare();
                }
            }

            Process[] my = Process.GetProcessesByName("mstsc");

            //loop thru list to get selected item(s)
            ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstOpenSessions);
            selectedItems = lstOpenSessions.SelectedItems;

            try
            {
                //remove credentials
                string szTestx = "/delete:GOJO.NET/" + cboServer.Text;
                ProcessStartInfo infox = new ProcessStartInfo("cmdkey.exe", szTestx);
                Process procx = new Process();
                procx.StartInfo = infox;
                procx.Start();

                if (lstOpenSessions.SelectedIndex != -1)
                {
                    for (int i = selectedItems.Count - 1; i >= 0; i--)
                    {
                        //loop thru process to match process vs. list selection(s)
                        foreach (Process remote in my)
                        {
                            if (remote.MainWindowTitle == selectedItems[i].ToString())
                            {
                                KillRS(remote.MainWindowTitle);
                                lstOpenSessions.Items.Remove(selectedItems[i]);
                            }
                        }

                        if (lstOpenSessions.Items.Contains(selectedItems[i].ToString()))
                        {
                            lstOpenSessions.Items.Remove(selectedItems[i]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} Exception caught.", ex);
            }
            // If your task is synchronous, then undo your flag here:
            runningExclusiveProcess = false;
            btnCloseSession.Enabled = true;
        }
    }
    public void KillLabWare()
    {
        ConnectionOptions con = new ConnectionOptions();
        con.Username = cboUserName.Text;
        con.Password = txtPassWord.Text;
        string strIPAddress = cboServer.Text;

        ManagementScope scope = new
            ManagementScope(@"\\" + strIPAddress + @"\root\cimv2", con);
        scope.Connect();
        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name='Labware.exe'");
        ManagementObjectSearcher searcher = new
            ManagementObjectSearcher(scope, query);
        ManagementObjectCollection objectCollection = searcher.Get();
        foreach (ManagementObject managementObject in objectCollection)
        {
            managementObject.InvokeMethod("Terminate", null);
        }
    }
    private void KillRS(string rwt)
    {
        foreach (Process p in Process.GetProcesses())
        {
            if (p.MainWindowTitle == rwt)
            {
                p.Kill();
            }
        }
    }
    public static void KillRemoteProcess(Process p, string user, string password)
    {
        new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "TaskKill.exe",
                Arguments = string.Format("/pid {0} /s {1} /u {2} /p {3}", p.Id, p.MachineName, user, password),
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true
            }
        }.Start();
    }

It sounds like you are trying to force a specific user to log out?听起来您试图强制特定用户注销? Is this because you find that users are forgetting to log out and constantly consuming licenses?这是因为您发现用户忘记注销并不断消耗许可证吗?

LabWare Application allows for a time out interval (in minutes) to be set on each user where after the interval has passed, the user will be logged out (licence no longer consumed). LabWare 应用程序允许为每个用户设置超时间隔(以分钟为单位),间隔过后,用户将被注销(不再消耗许可证)。 For more information see page 204 of the LabWare 7 Technical Manual.如需更多信息,请参见 LabWare 7 技术手册的第 204 页。

Alternativley if this is for a scheduler (service or cluster instance) session, this can also be controlled by the application.或者,如果这是用于调度程序(服务或集群实例)会话,这也可以由应用程序控制。 You can either manually change the shutdown and keep alive flags on the instance record on the Services table (if using Service Manager) or you can write a LIMS Basic event trigger/automation script or scheduled subroutine (or have this as a button on a Visual workflow) to do this for you.您可以手动更改服务表上实例记录上的关闭和保持活动标志(如果使用服务管理器),或者您可以编写 LIMS 基本事件触发器/自动化脚本或计划子例程(或将其作为可视化工具上的按钮)工作流)来为你做这件事。

HTH.哈。

If you wanna kill remote desktop session or disconnect current RDP session, please read this article: WTSDisconnectSession function如果您想终止远程桌面会话或断开当前 RDP 会话,请阅读这篇文章: WTSDisconnectSession 函数

but if you logout current user, it also disconnect RDP session, here is the code:但是如果您注销当前用户,它也会断开 RDP 会话,这是代码:

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;

class Program
{
  [DllImport("wtsapi32.dll", SetLastError = true)]
  static extern bool WTSDisconnectSession(IntPtr hServer, int sessionId, bool bWait);

  const int WTS_CURRENT_SESSION = -1;
  static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;

  static void Main(string[] args)
  {
    if (!WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE,
         WTS_CURRENT_SESSION, false))
      throw new Win32Exception();
  }
}

I hope it works, fill free for further info, comment plz我希望它有效,免费填写更多信息,请评论
Happy Coding 😎快乐编码😎

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM