1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python模拟鼠标点击和键盘输入的操作_Python模拟鼠标点击及键盘输入(PyUserInput)...

python模拟鼠标点击和键盘输入的操作_Python模拟鼠标点击及键盘输入(PyUserInput)...

时间:2018-09-30 17:45:23

相关推荐

python模拟鼠标点击和键盘输入的操作_Python模拟鼠标点击及键盘输入(PyUserInput)...

一、背景

有时可以通过程序来监控键盘或鼠标行为来触发鼠标的点击或者键盘的输入,类似于按键精灵,而Python是门简洁易实现的语言,同时PyUserInput库简单封装了底层的调用。

整篇文章以Windows为例。

二、PyUserInput简介

如果是Windows,底层依赖pywin32和pyHook。

三、环境流程Step.2 安装PyUserInput依赖环境:pywin32pip install pywin32,作用是执行键盘和鼠标操作

Step.3 安装PyUserInput依赖环境:pyHook然后pip install pyHook-1.5.1-cp27-none-win32.whl安装

Step.4 安装PyUserInputpip install PyUserInput

四、实战

假如想要实现鼠标左键双击时根据所在的不同区域实现不同的自动按键。

思路:监控鼠标事件,判断按键类型,如果是判断双击保留上一次的点击时间,自动按键最好新建线程,不然会卡在主线程。

#coding=utf-8

from pymouse import PyMouse, PyMouseEvent

from pykeyboard import PyKeyboard, PyKeyboardEvent

import time, threading

import math

## 初始化参数区(全局变量)

stop = False

interval = 1

is_running = False

times = 10

keys_mapping = {

0 : ['1', '2', '3', '4'],

10 : ['a', 'b'],

1 : ['c', 'd'],

11 : ['e', 'f'],

} # 左上:0 右上:10 左下:1 右下:11

mouse = PyMouse()

keyboard = PyKeyboard()

x_dim, y_dim = mouse.screen_size()

## 循环按键

def loop(key):

global stop

global is_running

global keyboard

is_running = True

for i in range(times):

for k in keys_mapping[key]:

if stop:

print('stop')

is_running = False

return

print(key, k)

#keyboard.tap_key(k)

time.sleep(interval)

is_running = False

## 监控鼠标

class Clickonacci(PyMouseEvent):

last_ts = None

last_x = None

last_y = None

last_button = None

def __init__(self):

PyMouseEvent.__init__(self)

## hori:1-上,-1-下

def scroll(self, x, y, hori, press):

print(x, y, hori)

def click(self, x, y, button, press):

if press:

return

global stop

global x_dim

global y_dim

ts = time.time()

# button:1-左键,2-右键,3-中键

# press: True-按下,False-释放

if button == 1:

## 判断双击

if self.last_ts and ts-self.last_ts<0.3 and self.last_button==button:

print('double click')

if is_running == True:

stop = True

time.sleep(interval)

stop = False

## 计算类型

key = 10*math.floor(2.0*x/x_dim) + math.floor(2.0*y/y_dim)

t = threading.Thread(target=loop, name='LoopThread', args=(key,))

t.start()

self.last_ts = ts

self.last_x = x

self.last_y = y

self.last_button = button

else:

stop = True

if __name__ == '__main__':

#main()

C = Clickonacci()

C.run()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。