服务器关闭或最小化远程桌面连接后,鼠标、键盘、剪切板等失效解决方法

你知唔知我系靓仔

服务器关闭或最小化远程桌面连接后,鼠标、键盘、剪切板等失效解决方法

根本原因

关闭远程桌面会让系统切换到登录Desktop的界面,而在登录Desktop的界面上没有我们打开的其他窗口,因此会导致鼠标、键盘、剪切板等失效,相当于被锁屏了,像pyautogui等图像匹配相关功能此时都会失效。

解决方法

在cmd运行代码:@%windir%\System32\tscon.exe 0 /dest:console,该命令会关闭远程桌面的连接,然后把连接返回给远程的那台电脑(绕开登录过程),其中0为远程连接时被分配的Session ID,一般Session ID不会大于10,除非有很多账户在你这台服务器上。

import subprocess
import threading
import time
from tkinter import Tk, StringVar, Entry, Label, Button, DISABLED

class CloseRDP:
    def __init__(self):
        self.window = Tk()
        self.window.title('退出远程桌面')
        self.window.geometry('300x150')
        self.window.resizable(False, False)
        self.text = StringVar()
        self.text.set('2')

        label1 = Label(self.window, text="定时:", font=('宋体', 25))
        self.entry = Entry(self.window, width=10, textvariable=self.text, font=('宋体', 20), fg='blue', justify='center')
        label2 = Label(self.window, text="秒", font=('宋体', 25))
        self.button = Button(self.window, width=13, height=3, text='开始', font=('黑体', 15), command=self.run)

        label1.grid(row=0, column=0)
        self.entry.grid(row=0, column=1)
        label2.grid(row=0, column=2)
        self.button.grid(row=1, column=1)
        self.window.protocol("WM_DELETE_WINDOW", self.close_window)  # 设置关闭窗口时的处理函数
        self.window.mainloop()

    def run(self):
        get_input = self.entry.get()
        if get_input.isdigit():
            self.button["text"] = "关闭软件取消"
            self.button['state'] = DISABLED
            self.entry.configure(state="readonly")
            t = threading.Thread(target=self.count_down, args=(int(get_input),))
            t.daemon = True  # 设置线程为守护线程
            t.start()

    def count_down(self, get_input):
        while get_input:
            time.sleep(1)
            get_input -= 1
            self.text.set(str(get_input))
        self.close_rdp()

    def close_rdp(self):
        for i in range(10):
            cmd = r'@%windir%\System32\tscon.exe {} /dest:console'.format(str(i))
            subprocess.Popen(cmd, shell=True)
        self.window.destroy()

    def close_window(self):
        self.window.destroy()
        self.close_rdp()

if __name__ == '__main__':
    CloseRDP()

程序和文章来自https://blog.csdn.net/qq_51038274/article/details/122223669

修改解决了一些因为setDaemon方法引起的异常