Python利用pynput实现划词复制功能

前言

本文参考了以下代码

Windows系统环境下Python脚本实现全局“划词复制”功能

from pynput import mouse
import time
import threading

__DEBUG = False

def log(msg,debug=False):
    if __DEBUG or debug:
        print(msg)

class MouseMonitor():
    __press_time = 0
    __press_double_state = False
    __move = (0,0)

    def __init__(self,on_selected=None):
        if on_selected:
            self.on_selected = on_selected
        else:
            self.on_selected = self.on_selected

        self.listener = mouse.Listener(on_move=self.on_move,on_click=self.on_click)
        self.listener.start()
        self.listener.join()

    def on_selected(msg):
        print('selected "%s" has been copied.' % (msg,))

    def on_move(self,x,y):
        if self.__press_time == 0:
            self.__move = (x,y)
        # log(self.__press_time,time.time())
        # log('Pointer moved to {0}'.format((x,y)))

    def on_click(self,x,y,button,pressed):
        if str(button) == 'Button.left':
            if pressed:
                self.on_pressed(x,y)
            else:
                self.on_released(x,y)

    def on_pressed(self,x,y):
        if self.__press_double_state:
            # double click
            # self.__press_double_state = False
            if not self.check_not_time_out(self.__press_time, time.time(),0.4): # miss double click
                log('double1 click timeout and reset then')
                self.reset()
                self.__press_time = time.time()
        else:
            # single click
            self.__press_time = time.time()
            # self.__press_double_state = False

    def on_released(self,x,y):
        if self.__press_double_state:
            # double click
            if self.check_not_time_out(self.__press_time, time.time(),0.8):
                log('double click: %s' % (self.get_copy()))
                self.on_selected(self.get_copy())
                self.__press_double_state = False
            else:
                log('double2 click timeout and reset then')
                self.reset()
        else:
            if self.check_not_time_out(self.__press_time, time.time()):
                log('double click maybe')
                self.__press_double_state = True
                threading.Timer(0.5, self.timeout_handler).start() # wait timeout to reset
            elif not self.check_not_time_out(self.__press_time, time.time(),1):
                if self.__move != (0,0):
                    self.on_selected(self.get_copy())
                    log('selected: %s' % (self.get_copy(),))
                    self.reset()
            else:
                log('reset state')
                self.reset()

    def get_copy(self):
        import win32clipboard as wc
        import win32con

        def trigger_copy():
            from pynput.keyboard import Key,Controller
            key = Controller()
            with key.pressed(Key.ctrl):
                key.press('c')
                key.release('c')
            time.sleep(0.1) # wait for ctrl+c valid

        trigger_copy()
        msg = ''
        try:
            wc.OpenClipboard()
            msg = wc.GetClipboardData(win32con.CF_UNICODETEXT)
            wc.CloseClipboard()
        except TypeError:
            log('Clipboard Content is TypeError.')
        return msg

    def reset(self):
        self.__press_time = 0
        self.__press_double_state = False
        self.__move = (0,0)

    def timeout_handler(self):
        self.reset()
        log('timeout reset state')

    def check_not_time_out(self,old,new,delta=0.2):
        if(new - old > delta): # time delta > 0.2s
            return False
        else:
            return True


def printf(msg):
    log('copy content:'+msg,True)
    # log('x = {0} , y = {1}'.format(x,y))


if __name__ == '__main__':
    mm = MouseMonitor(printf)

pynput库的官方文档

实现代码

参考的博客实现了划词复制,但是看了下他的代码写的有点复制混乱,监听准确率并不高且不太容易理解。

实际监听鼠标的划词操作逻辑很简单:

记录下鼠标左键按下时的位置,当鼠标左键松开时,记录下鼠标左键松开的位置,如果按下的位置和松开的位置不一致,说明鼠标正在划词。

from pynput.mouse import Listener, Button
from pynput.keyboard import Key, Controller
 
class AutoCopier():
    __press_xy = (0, 0)  # 私有变量 鼠标左键按下时的位置
 
    def __init__(self):
        self.keyboard = Controller()                     # 初始化键盘控制器
        self.listener = Listener(on_click=self.on_click) # 初始化鼠标监听器
        self.listener.start()                            # 开启鼠标监听器线程
 
    # 点击函数
    def on_click(self, x, y, button, pressed):           
        if button == Button.left:             # 左键点击
            if pressed:                       # 左键按下
                self.__press_xy = (x, y)      # 记录当前鼠标位置
            else:                             # 左键松开           
                if self.__press_xy != (x, y): # 按下位置和松开位置不一致
                    self.copy()               # 说明操作是划词,执行复制函数
    
    # 复制函数
    def copy(self): 
        with self.keyboard.pressed(Key.ctrl): # 按下ctrl,with语句结束后自动松开
            self.keyboard.press('c')          # 按下c
            self.keyboard.release('c')        # 松开c
 
    # 等待线程终止
    def wait_to_stop(self):
        self.listener.join()
 
# for test
if __name__ == '__main__':
    at = AutoCopier()
    at.wait_to_stop()

知识点补充

1.pynput是什么

官方说法:“他可以控制和监听我们的输入设备,目前支持鼠标和键盘的控制与监听;因为我只使用了设备的控制 至于监听并没作深入了解 文章也不设计”

2.使用步骤

安装pynput模块

pip install pynput
#使用ctrl+v 快捷粘贴时候用到
pip install pyperclip

键盘控制

如下:

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

keyboard = c_keyboard()
#字符与数字
keyboard.press('a')
keyboard.release('a')

keyboard.press('A')
keyboard.release('A')

keyboard.press('1')
keyboard.release('1')
#非数字与字母键 详情: https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key
keyboard.press(Key.enter);
keyboard.release(Key.enter);
#组合
##全选
keyboard.press(Key.ctrl)
keyboard.press('a')
time.sleep(2)
keyboard.release('a')
keyboard.release(Key.ctrl)
###或者
with keyboard .pressed(Key.ctrl):
 keyboard.press('a')
 keyboard.release('a')
##复制
seller_nick = 'www.baidu.com/a.php?a=a&b=2'
pyperclip.copy('https://'+seller_nick.replace('amp;',''))
##粘贴
keyboard.press(Key.ctrl)
keyboard.press('v')
time.sleep(1)
keyboard.release('v')
keyboard.release(Key.ctrl)
##回车
keyboard.press(Key.enter);
keyboard.release(Key.enter);

鼠标控制

如下:

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

mouse= c_mouse()
#点击
##双击
mouse.click(Button.left, 2)
##按下右键
mouse.press(Button.right)
##释放右键
mouse.release(Button.right)
#鼠标坐标
print(mouse.position) 
##x轴坐标
print(mouse.position[0]) 
##y轴坐标
print(mouse.position[1])
#移动
##移动到绝对坐标
mouse.position = (400, 38)
##相对当前坐标移动
mouse.move(300, 2)
#滑动
mouse.press(Button.left)
mouse.move(300, 2)
mouse.release(Button.left)

到此这篇关于Python利用pynput实现划词复制功能的文章就介绍到这了,更多相关Python pynput划词复制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Python利用pynput实现划词复制功能)