【问题标题】:How would I tell if my user has focus on the terminal?我如何判断我的用户是否专注于终端?
【发布时间】:2021-07-12 07:28:24
【问题描述】:

我正在通过 GUI 使用 CLI 创建聊天室应用程序,并且我在 Windows 上,所以我只使用命令提示符中的默认终端来运行我的代码。我的程序检测到单个按键,然后将它们添加到我的数据类中的列表中,该列表在加入时会创建用户的消息。我在这里遇到的唯一问题是程序即使在没有焦点的情况下也会记录按键。有什么方法可以检测终端是否在焦点上,以便我可以适当地处理按键?我现在所拥有的基本上是一个意外的键盘记录器。

我的代码(虽然对我觉得应该添加它以防万一的问题没有用处):

import json, keyboard, os, socket, termcolor, threading



def addKey(key):
    data.line.append(key)
    data.lineLength += 1



def cls():
    os.system("cls")



def display_chatLog():

    return "\n".join(data.chatLog)



def display_lineLength():

    return f"Characters: {data.lineLength}/{data.maxLineLength}\n\n"



def display_userInput():

    return f"\n{data.start} {''.join(data.line)}{data.end}\n"



def enterPressed():
    joinLine = " ".join(data.line)

    if data.server:

        if data.lineLength <= data.maxLineLength:
            data.server.send(bytes(f"{data.username}: {joinLine}", "utf-8"))
            data.line = []

        else:
            data.warning = "Your message is too long"

    else:

        if data.line[0] == "host":
            port = data.line[1]

        else:
            IP = data.line[1]
            port = data.line[2]



def getKeys():
    specialKeys = ("backspace", "ctrl", "enter", "esc", "shift", "right shift", "space")

    while True:
        key = keyboard.read_event()
        keyType = key.event_type
        keyName = key.name

        if keyType == "down":

            if keyName not in specialKeys:
                addKey(keyName)

            elif keyName == "backspace":

                if len(data.line) > 0:

                    del data.line[len(data.line) - 1]

                    data.lineLength -= 1

            elif keyName == "enter":
                enterPressed()

            elif keyName == "shift":

                if keyboard.is_pressed(f"shift+{keyName}") and keyName not in specialKeys:
                    addKey(keyName.upper)

            elif keyName == "space":
                addKey(" ")



class data:
    chatLog = []
    end = "_"
    line = []
    lineLength = 0
    maxLineLength = 512
    server = None
    start = ">>>"
    warning = "Make sure to either host a server using 'host (port)' or join one by using 'join (IP adress) (port)'"



getKeys_thread = threading.Thread(target = getKeys)
getKeys_thread.start()



while True:
    cls()
    print(display_chatLog(), display_userInput(), display_lineLength(), "\n", termcolor.colored(data.warning, "red", "on_white"))

【问题讨论】:

  • 假设用户使用网络浏览器,这听起来像是 JavaScript 问题,而不是 Python 或 Django 问题。
  • 这是一个学校项目,其中每个用户都 100% 保证从 Windows 的默认终端运行程序,但我理解你的意思,它适用于不同的情况。谢谢!

标签: python-3.x keyboard-python


【解决方案1】:
import ctypes

def getWindow():
    hwnd = ctypes.windll.user32.GetForegroundWindow()
    length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
    buff = ctypes.create_unicode_buffer(length + 1)
    ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
    return (buff.value, hwnd) # buff.value is the title of the window, hwnd is the window handle

我从here 获得并稍微编辑的这段代码允许我捕获当前聚焦窗口的名称和窗口句柄。

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2011-03-25
    • 1970-01-01
    • 2012-02-13
    • 2017-08-16
    • 2011-03-14
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多