Mac Cocoa: How to differentiate if a NSScrollWheel event is from a mouse or trackpad?

点点圈 提交于 2019-11-30 13:49:25
AProgrammer

-[NSEvent momentumPhase] is the solution. So, the events generated from the trackpad between the beginGesture and endGesture events returns a value other than NSEventPhaseNone for -[NSEvent phase] and the trackpad events that are generated after the endGesture event returns a value other than NSEventPhaseNone for -[NSEvent momentumPhase]. The code is below,

 - (void)scrollWheel:(NSEvent *)theEvent
    {
       if(([theEvent momentumPhase] != NSEventPhaseNone) || [theEvent phase] != NSEventPhaseNone))
       {
          //theEvent is from trackpad           
       }
       else 
       {
         //theEvent is from mouse
       }
    }

You can use [event hasPreciseScrollingDeltas] to differentiate. It was added in OS X Lion. It differentiates between line scroll (mouse wheels) and pixel scroll (trackpads, magic mouse) events.

My answer in Swift, but for Objective C logic is the same:

override func scrollWheel(with event: NSEvent) {
  if event.subtype == .mouseEvent {
    // mouse
  } else {
    // trackpad
  }
}

The answer given by @AProgrammer maybe not available. Because scrollwheel event generated by magic mouse has phase values of: began, changed and ended. And scrollwheel event generated by mighty mouse has value of none for both phase and momentumphase. So the method can only distinguish mighty mouse from magic mouse and trackpad.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!