Hide mouse cursor on OS X after a few seconds
For my fullscreen app, I want to hide the cursor after a few seconds if it's not moved, like the fullscreen mode in QuickTime or iTunes. Presumably I'm looking to call [NSCursor setHiddenUntilMouseMoves:YES]
, but how do I know when to call it?
Presumably I'm looking for the same as开发者_JS百科 Hide mouse cursor after an idle time but on the Mac. I couldn't find a way to get similar a "idle time". (Plus, I probably don't care about keyboard events, just mouse movement.)
You can get the time the cursor (and if you want also the keyboard) has been idle using:
CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateCombinedSessionState, kCGEventMouseMoved)
Swift 3 code:
CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.combinedSessionState, eventType: CGEventType.mouseMoved)
See also http://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html. You're probably going to have to poll this function every couple of seconds, and you should assume the user moved the cursor if the time returned has decreased.
What about using NSTimer and check after n seconds whether nothing has happened?
You can set NSCursor.setHiddenUntilMouseMoves(true)
, for e.g.:
import Cocoa
class MyWindowController: NSWindowController {
private var mouseTimer: Timer?
private var mouseTimeOut: Float = 1.0
override func awakeFromNib() {
mouseTimer = Timer.scheduledTimer(timeInterval: TimeInterval(mouseTimeOut),
target: self,
selector: #selector(hideMouse),
userInfo: nil,
repeats: true)
}
// MARK: - Mouse Cursor
@objc func hideMouse() {
if Float(CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.combinedSessionState, eventType: CGEventType.mouseMoved)) > mouseTimeOut {
NSCursor.setHiddenUntilMouseMoves(true)
}
}
}
精彩评论