Kill Certain MSTSC Process

779 views Asked by At

Is there a way to kill certain instances of the mstsc process.

For example, I rdp to pc1.xyz.com.au and pc2.xyz.com.au.

Now from c#, I want to kill or disconnect pc1.xyz.com.au.

Currently the code below kills all the instances of mstsc process. Is there any way I can disconnect only certain mstsc instances.

 private void terminateRDP()
        {
            foreach (var process in Process.GetProcessesByName("mstsc"))
            {
                process.Kill();
            }
        }

I tried saving the pid of the process that is opened but the capture pid that i captured is different than the one in the task bar. I am opening a .rdp file using code below.

Process rdcProcess = new Process();
                    rdcProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
                    rdcProcess.StartInfo.Arguments = "/generic:TERMSRV/" + server + " /user:" + username + " /pass:" + password;
                    rdcProcess.Start();
                    rdcProcess.WaitForExit();

                    changeServerRDP(serverAddress);
                    if (getApplicationPath(serverList.SelectedItem.ToString()) != String.Empty)
                    {
                        changeServerRDPPath(getApplicationPath(serverList.SelectedItem.ToString()));
                        rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");                      
                        rdcProcess.StartInfo.Arguments = "C:\\rdp\\my.rdp";
                        rdcProcess.Start();
                        rdcProcess.WaitForExit();

                        //pids.Add(rdcProcess.Id);
                        //int procID = rdcProcess.Id;
                        //MessageBox.Show(procID.ToString());
                        //opened.Add(rdcProcess);

                    }
1

There are 1 answers

0
Ankit Vijay On

If you need to terminate RDP session, You can try: WTSDisconnectSession API

This stackoverflow link explains how to use it in C#