我想使用鼠标和键盘的特定组合来捕获屏幕的一部分。
我获得了捕获屏幕的功能,我所需要的只是某种方式来对鼠标和键盘的组合做出反应,例如:Ctrl + Shift +鼠标在特定区域拖动。
对于鼠标拖动到特定区域,我需要执行以下操作,检查是否按住 Ctrl+Shift,然后在单击鼠标后立即记录鼠标坐标(用户开始单击并拖动该区域(和释放单击时的坐标(用户完成选择区域(...我需要这四个坐标来进行屏幕捕获功能
下面是一些相关的不完整代码。我只需要 on_press(( 的函数来实现我的目标
from pynput.keyboard import Key, Listener
from pynput.mouse import Listener
def on_press(key):
#Here i want to do the listening stuff and recording the mousepositions
def on_release(key):
if key == Key.ctrl_l:
if key == Key.shift:
return False
if key == Key.shift:
if key == Key.ctrl_l:
return False
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
#x is the list which contains the relevant recorded coordinates
x=[top_left_x,top_left_y,bottom_right_x,bottom_right_y]
screen = grab_screen(region=(x[0],x[1],x[2],x[3]))
cv2.imshow('window',screen)
请帮帮我...如果您对抓取屏幕功能代码感兴趣在这里:
import cv2
import numpy as np
import win32gui, win32ui, win32con, win32api
def grab_screen(region=None):
hwin = win32gui.GetDesktopWindow()
if region:
left,top,x2,y2 = region
width = x2 - left + 1
height = y2 - top + 1
else:
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
signedIntsArray = bmp.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
img.shape = (height,width,4)
srcdc.DeleteDC()
memdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
win32gui.DeleteObject(bmp.GetHandle())
return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
这应该会有所帮助。COMBINATION
列表是组合中的键列表。
from pynput import keyboard
# The key combination to check
COMBINATION = {keyboard.Key.shift, keyboard.Key.ctrl, keyboard.Key.alt, keyboard.KeyCode.from_char('x')}
# The currently active modifiers
current = set()
def on_press(key):
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION):
print('All modifiers active!')
if key == keyboard.Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
它可以工作,但如果在侦听器启动之前按下其中一个修饰键,则必须释放并再次按下它才能让程序检测到它。