用ESC键中断CGPostMouseEvent循环

问题描述

我需要通过按下键盘来中断Quartz.CoreGraphics.CGPostMouseEvent for loop,但是当我进入CGPostMouseEvent的for循环时,似乎无法检测到按键。我尝试使用time.sleep代码底部)尝试相同的代码来检测按下的键。我不是Quartz的专家,所以如果我做错了这件事,我深表歉意,但是我不能使用CGEventCreateMouseEvent,pyautogui和pynput,因为它们不能在3D视口CGEventPost does not always move the mouse macOS

中工作
import math,time
from Quartz.CoreGraphics import CGPostMouseEvent
from pynput import keyboard


def orbit(x,y,r=10,loops=10,speed=10):
    """
    This method updates the mouse position in a 3D Viewport. It is necessary to use CGPostMouseEvent:
        https://stackoverflow.com/questions/45313432/cgeventpost-does-not-always-move-the-mouse-macos
    """
    r = 10
    for i in range(1,360*loops,speed):
        # if keyboard.is_pressed('space'):
            # print('something')
            # sys.exit()
            # break
        x = x + r * math.cos(math.radians(i))
        y = y + r * math.sin(math.radians(i))
        CGPostMouseEvent((x,y),True,1,True)
        time.sleep(0.02)

def on_key_press(key):
    """
    Method to quit the App while reproducting a macro
    """
    print(key)
    if key == keyboard.Key.esc:
        print('ESC KEY pressed')

if __name__ == "__main__":
    """
    When the orbit method is exectued the mouse moves away form the the python terminal loosing focus,therefore Ctrl-C cannot interrupt the program.
    I would like to allow the user to interrupt the execution by pressing ESC at any time,so I have created a listnener which works in any portion of the screen,but it stops working when I inside the "orbit".
    """
    listener_thread = keyboard.Listener(on_press=on_key_press,deamon=True)
    listener_thread.start()
    # listener_thread.join()
    
    # LOOP RUNNING MOUSE MACRO. This code doesn't work with the keyboard listener
    orbit(1744*0.5,1344*0.5)

    # This code works with tle listener
    # for i in range(10):
    #     time.sleep(1)
    #     print(i)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)