简体   繁体   中英

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). For more information see page 204 of the LabWare 7 Technical Manual.

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.

HTH.

If you wanna kill remote desktop session or disconnect current RDP session, please read this article: WTSDisconnectSession function

but if you logout current user, it also disconnect RDP session, here is the code:

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 😎

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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