如何以编程方式同时按下“ shift” +“ command” +“ 3”

时间:2019-03-12 11:59:54

标签: macos cocoa keyboard nsevent

我正试图通过发布此Keyboard事件来捕获屏幕截图。我尝试了以下不起作用的方法:-

1]

CGEventRef event1, event2, event3, event4, event5, event6;
event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, true);
event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)55, true);
event3 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)85, true);//or 20
event4 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)85, false);// or 20
event5 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)55, false);
event6 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, false);

CGEventPost(kCGSessionEventTap, event1);
CGEventPost(kCGSessionEventTap, event2);
CGEventPost(kCGSessionEventTap, event3);

CGEventPost(kCGSessionEventTap, event4);
CGEventPost(kCGSessionEventTap, event5);
CGEventPost(kCGSessionEventTap, event6);

CFRelease(event1);
CFRelease(event2);
CFRelease(event3);
CFRelease(event4);
CFRelease(event5);
CFRelease(event6);

2]

CGEventRef event7;
event7 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)85, true);//or 20
CGEventSetFlags(event7, kCGEventFlagMaskShift);
CGEventSetFlags(event7, kCGEventFlagMaskCommand);
CGEventPost(kCGSessionEventTap, event7);
CFRelease(event7);

两者都不起作用。建议我任何好的选择

1 个答案:

答案 0 :(得分:2)

1]不起作用,因为您未设置事件标志。 2]不起作用,因为您没有发布按键事件,并且CGEventSetFlags(event7, kCGEventFlagMaskCommand);替换了kCGEventFlagMaskShift标志。设置两个标志:

CGEventRef event7;
event7 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)85, true);//or 20
CGEventSetFlags(event7, kCGEventFlagMaskShift | kCGEventFlagMaskCommand);
CGEventPost(kCGSessionEventTap, event7);
CFRelease(event7);

event7 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)85, false);//or 20
CGEventSetFlags(event7, kCGEventFlagMaskShift | kCGEventFlagMaskCommand);
CGEventPost(kCGSessionEventTap, event7);
CFRelease(event7);