Grant Wilkinson
Grant Wilkinson

Reputation: 1128

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)
    {

    }
}

Upvotes: 3

Views: 3967

Answers (3)

Antoine Rosset
Antoine Rosset

Reputation: 1065

Starting with OS X 10.6, you can use NSEvent’s pressedMouseButtons method from anywhere:

NSUInteger mouseButtonMask = [NSEvent pressedMouseButtons];
BOOL leftMouseButtonDown = (mouseButtonMask & (1 << 0)) != 0;
BOOL rightMouseButtonDown = (mouseButtonMask & (1 << 1)) != 0;

The method returns indices of the mouse buttons currently down as a mask. 1 << 0 corresponds to the left mouse button, 1 << 1 to right mouse button, and 1 << n, n >= 2 to other mouse buttons.

With this it’s not necessary to catch the mouseDown:, mouseDragged:, or mouseUp: events.

Upvotes: 11

jscs
jscs

Reputation: 64022

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.
}

Upvotes: 5

As far as I remember the mouseDown is only fired when the user first clicks the element, not when held down.

The solution to your problem is to define a BOOL in your .h like so:

bool mouseIsHeldDown = false;

Then in your mouseDown:

mouseIsHeldDown = true;

And in your mouseUP:

mouseIsHeldDown = false;

You can then check if mouseIsHeldDown = true anywhere in your code.

Hope this fixes your problem!

Upvotes: 0

Related Questions