Grant Wilkinson Grant Wilkinson - 3 months ago 19
Objective-C Question

Detect mouse being held down

I am trying to be able to detect when a mouse is held down instead of clicked. This is what I have, but instead of a click count I want to be able to detect the mouse being held down.

-(void)mouseDown:(NSEvent *)event;
{
//instead of clickCount I want my if statement to be
// if the mouse is being held down.
if ([event clickCount] < 1)
{

}
else if ([event clickCount] > 1)
{

}
}

Answer

Presumably you want to detect whether the mouse is being held down for a certain period of time. This is pretty straightforward; it just requires a timer.

In your mouseDown:, you start a timer which will fire after your chosen period. You need to stick this into an ivar, because you will also refer to it in mouseUp:

- (void)mouseDown: (NSEvent *)theEvent {
    mouseTimer = [NSTimer scheduledTimerWithTimeInterval:mouseHeldDelay
                                                  target:self
                                                selector:@selector(mouseWasHeld:)
                                                userInfo:theEvent
                                                 repeats:NO];
}

In mouseUp:, destroy the timer:

- (void)mouseUp: (NSEvent *)theEvent {
    [mouseTimer invalidate];
    mouseTimer = nil;
}

If the timer fires, then you know that the mouse button has been held down for your specified period of time, and you can take whatever action you like:

- (void)mouseWasHeld: (NSTimer *)tim {
    NSEvent * mouseDownEvent = [tim userInfo];
    mouseTimer = nil;
    // etc.
}