Skip to content

Commit

Permalink
分离出鼠标监听接口
Browse files Browse the repository at this point in the history
  • Loading branch information
hiroi-sora committed Nov 1, 2022
1 parent 492391d commit 8b25904
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
16 changes: 8 additions & 8 deletions ui/win_screenshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,17 @@ def __initKey(self): # 初始化监听
# 绑定全局事件
Hotkey.addRelease( # Esc抬起,系统截图失败
'esc', lambda: self.__close(False))
mouse.on_button(self.__onDown, # 左键和右键按下,开始截图
buttons=('left', 'right'), types='down')
mouse.on_button(self.__onUp, # 左键和右键抬起,截图可能成功可能失败
buttons=('left', 'right'), types='up')
Hotkey.addMouseButtonDown(self.__onDown) # 注册监听鼠标左/右按下
Hotkey.addMouseButtonUp(self.__onUp) # 注册监听鼠标左/右抬起
self.isInitKey = True

def __onDown(self, e=None): # 用户操作开始
def __onDown(self, pos): # 用户操作开始
if self.isWorking:
self.position = mouse.get_position() # 获取鼠标当前位置
self.position = pos # 获取鼠标当前位置

def __onUp(self, e=None): # 用户操作结束
def __onUp(self, pos): # 用户操作结束
if self.isWorking:
if self.position == mouse.get_position(): # 鼠标起始结束位置相同,截图失败
if self.position == pos: # 鼠标起始结束位置相同,截图失败
self.__close(False)
return
self.checkTime = 0
Expand All @@ -105,6 +103,8 @@ def __checkClipboard(self): # 检查剪贴板中是否已存在截图

def __close(self, flag=False): # 退出
if self.isWorking:
Hotkey.removeMouse() # 注销监听鼠标
self.isInitKey = False
self.isWorking = False
_ScreenshotClose(flag)

Expand Down
25 changes: 25 additions & 0 deletions utils/hotkey.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from utils.pynput_hotkey import hotkeyApi
from utils.logger import GetLog

import mouse # 绑定鼠标键


Log = GetLog()

Expand Down Expand Up @@ -43,6 +45,29 @@ def send(hotkey):
hotkeyApi.send(hotkey)
Log.info(f'发送按键组合【{hotkey}】')

@staticmethod
def addMouseButtonDown(callback):
'''添加一个鼠标按钮监听。按下时调用callback,返回xy坐标元组'''
def cb():
pos = mouse.get_position() # 获取鼠标当前位置
callback(pos)
mouse.on_button(cb,
buttons=('left', 'right'), types='down')

@staticmethod
def addMouseButtonUp(callback):
'''添加一个鼠标按钮监听。松开时调用callback,返回xy坐标元组'''
def cb():
pos = mouse.get_position() # 获取鼠标当前位置
callback(pos)
mouse.on_button(cb,
buttons=('left', 'right'), types='up')

@staticmethod
def removeMouse():
'''移除鼠标监听'''
mouse.unhook_all()


"""
# 旧版热键类。依赖 keyboard 库,这个库年久失修Bug多,弃之。
Expand Down

0 comments on commit 8b25904

Please sign in to comment.