如何创建NSScrollWheel类型的NSEvent?

smo*_*ris 14 macos cocoa objective-c

我想构造(伪造)NSScrollWheel类型的NSEvent.有一些NSEvent构造函数方法用于其他几种类型的NSEvent(mouseEvent,keyEvent,enterExitEvent,otherEvent),但是没有一个允许我设置,例如deltaX.

ugh*_*fhw 11

NSEvent没有提供这样做的方法,但您可以创建一个CGEvent并在其周围创建一个NSEvent包装器.该事件将自动使用光标的当前位置.请参阅CGEventCreateScrollWheelEvent.但是,使用NSApplication发布此事件postEvent:atStart:不起作用(可能是因为它没有定义窗口).您可以将CGEvent直接发布到事件流,也可以将NSEvent直接发送到视图的scrollWheel:方法.

CGWheelCount wheelCount = 2; // 1 for Y-only, 2 for Y-X, 3 for Y-X-Z
int32_t xScroll = ?1; // Negative for right
int32_t yScroll = ?2; // Negative for down
CGEventRef cgEvent = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, wheelCount, yScroll, xScroll);

// You can post the CGEvent to the event stream to have it automatically sent to the window under the cursor
CGEventPost(kCGHIDEventTap, cgEvent);

NSEvent *theEvent = [NSEvent eventWithCGEvent:cgEvent];
CFRelease(cgEvent);

// Or you can send the NSEvent directly to a view
[theView scrollWheel:theEvent];
Run Code Online (Sandbox Code Playgroud)