python 鼠标键盘监听

骑猪看日落 2022-05-17 11:43 639阅读 0赞

pyHook手册: http://pyhook.sourceforge.net/doc_1.5.0/
可以检测全局键盘输入,但是鼠标只能在当前窗口,一旦鼠标移出当前窗口程序就停止运行
from ctypes import *
import pyHook
import pywin32_postinstall
import pythoncom
import threading
import time
import sys
import win32api
import pyautogui as pag
global x_ #存储按键操作

global result 全局变量result

def onMouseEvent(event):
x_f = open(“X坐标.txt”, ‘a’, encoding=”utf-8”)
y_f = open(“Y坐标.txt”, ‘a’, encoding=”utf-8”)
#print(“MessageName:”,event.MessageName) #检测鼠标是否移动
#print (“Message:”,event.Message) # 打印512不知道是什么东西
#print (“Time:”,event.Time) #1307132不知道什么东西
#print (“Window:”,event.Window) #66592不知道什么东西
#print (“WindowName:”,event.WindowName) #不知道什么东西

  1. #kprint("WindowName:%s\n",event.WindowName)
  2. x_y=event.Position
  3. print(x_y)
  4. #print ("Position:",event.Position) #当前X轴 Y轴
  5. #print ("Wheel:",event.Wheel)
  6. #print ("Injected:",event.Injected)
  7. print(x_y[0],x_y[1])
  8. x_f.write(repr(x_y[0])+"\n")
  9. y_f.write(repr(x_y[1])+"\n")
  10. return True

def onKeyboardEvent(event):
# 监听键盘事件
# print (“MessageName:”, event.MessageName)
# print (“Message:”, event.Message)
# print (“Time:”, event.Time)
# print (“Window:”, event.Window)
# print (“WindowName:”, event.WindowName)
# print (“Ascii:”, event.Ascii, chr(event.Ascii))
# print (“Key:”, event.Key)
# print (“KeyID:”, event.KeyID)
# print (“ScanCode:”, event.ScanCode)
# print (“Extended:”, event.Extended)
# print (“Injected:”, event.Injected)
# print (“Alt”, event.Alt)
# print (“Transition”, event.Transition)
x_=event.Key #键盘输入的值
print(“按键:”,x_)
if x_==’Numpad1’:
win32api.PostQuitMessage(0) # 结束监听
return True
# 创建一个“钩子”管理对象
hm = pyHook.HookManager()

  1. # 监听所有的键盘事件
  2. hm.KeyDown = onKeyboardEvent
  3. # 设置键盘”钩子“
  4. hm.HookKeyboard()
  5. #检测到鼠标按下
  6. hm.MouseAllButtonsDown = onMouseEvent
  7. #检测到鼠标弹起
  8. hm.MouseAllButtonsUp = onMouseEvent
  9. # 监听所有鼠标事件(移动的所有坐标打印输出)
  10. # hm.MouseAll = onMouseEvent
  11. #设置鼠标钩子
  12. hm.HookMouse()
  13. # 进入循环,如不手动关闭,程序将一直处于监听状态
  14. # 12:每个循环时间
  15. pythoncom.PumpMessages(12)

鼠标移动,点击参考:https://www.cnblogs.com/eatPython/p/5958850.html

发表评论

表情:
评论列表 (有 0 条评论,639人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Processing鼠标键

    一、鼠标 1、鼠标坐标: Processing的2D坐标系统,是以窗口的左上角为起点,作为(0, 0)点,x轴正方向向右延伸,y轴正方向向下延伸。而描述鼠标的位置信息,用的