这是我的代码:
CGEventSourceRef src =
CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef cmdd = CGEventCreateKeyboardEvent(src, 0x37, true);
CGEventRef cmdu = CGEventCreateKeyboardEvent(src, 0x37, false);
CGEventRef sftd = CGEventCreateKeyboardEvent(src, 0x38, true);
CGEventRef sftu = CGEventCreateKeyboardEvent(src, 0x38, false);
CGEventRef fourd = CGEventCreateKeyboardEvent(src, 0x15, true);
CGEventRef fouru = CGEventCreateKeyboardEvent(src, 0x15, false);
CGEventSetFlags(fourd, kCGEventFlagMaskCommand); //NO idea why this is here.
CGEventSetFlags(fouru, kCGEventFlagMaskCommand); //NO idea why this is here.
CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works
CGEventPost(loc, cmdd); //Cmd down
CGEventPost(loc, sftd); //Shift down
CGEventPost(loc, fourd); //4 down
CGEventPost(loc, cmdu); //Cmd up
CGEventPost(loc, sftu); //Shift up
CGEventPost(loc, fouru); //4 up
CFRelease(cmdd);
CFRelease(cmdu);
CFRelease(sftd);
CFRelease(sftu);
CFRelease(fourd);
CFRelease(fouru);
CFRelease(src);
}
有谁能告诉我为什么这不起作用?它按下按钮执行命令Cmd + Shft + 4并允许用户执行屏幕截图功能。
答案 0 :(得分:1)
您缺少为cmd / shift / 4键击设置的一些标志。
CGEventSourceRef src = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); CGEventRef cmdd = CGEventCreateKeyboardEvent(src, 0x37, true); CGEventRef cmdu = CGEventCreateKeyboardEvent(src, 0x37, false); CGEventSetFlags(cmdd, kCGEventFlagMaskCommand); CGEventSetFlags(cmdu, kCGEventFlagMaskCommand); CGEventRef sftd = CGEventCreateKeyboardEvent(src, 0x38, true); CGEventRef sftu = CGEventCreateKeyboardEvent(src, 0x38, false); CGEventSetFlags(sftd, kCGEventFlagMaskShift); CGEventSetFlags(sftu, kCGEventFlagMaskShift); CGEventRef fourd = CGEventCreateKeyboardEvent(src, 0x15, true); CGEventRef fouru = CGEventCreateKeyboardEvent(src, 0x15, false); CGEventSetFlags(fourd, kCGEventFlagMaskCommand ^ kCGEventFlagMaskShift); CGEventSetFlags(fouru, kCGEventFlagMaskCommand ^ kCGEventFlagMaskShift); CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works CGEventPost(loc, sftd); //Shift down CGEventPost(loc, cmdd); //Cmd down CGEventPost(loc, fourd); //4 down CGEventPost(loc, fouru); //4 up CGEventPost(loc, sftu); //Shift up CGEventPost(loc, cmdu); //Cmd up CFRelease(cmdd); CFRelease(cmdu); CFRelease(sftd); CFRelease(sftu); CFRelease(fourd); CFRelease(fouru); CFRelease(src);