Detect mouse
I am trying to detect when the mouse is being held down instead of clicking. This is what I have, but instead of the number of clicks, I want to detect that the mouse is 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)
{
}
}
source to share
Presumably, you want to determine if the mouse is being held down for a certain period of time. It's pretty simple; it just requires a timer.
In yours, mouseDown:
you start a timer that will fire after the period you choose. You need to insert this into the ivar because you will also be linking to it inmouseUp:
- (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, you know that the mouse button is held down for the specified period of time, and you can take any action you like:
- (void)mouseWasHeld: (NSTimer *)tim {
NSEvent * mouseDownEvent = [tim userInfo];
mouseTimer = nil;
// etc.
}
source to share
Since OS X 10.6, you can use the NSEvent
s method pressedMouseButtons
from anywhere:
NSUInteger mouseButtonMask = [NSEvent pressedMouseButtons];
BOOL leftMouseButtonDown = (mouseButtonMask & (1 << 0)) != 0;
BOOL rightMouseButtonDown = (mouseButtonMask & (1 << 1)) != 0;
The method returns the indices of the mouse buttons currently down as a mask. 1 << 0
corresponds to the left mouse button, 1 << 1
to the right mouse button, and 1 << n
n> = 2 to other mouse keys.
In this case, you do not need to catch events mouseDown:
, mouseDragged:
or mouseUp:
.
source to share
As far as I remember, mouseDown only fires when the user first clicks on the element, not when held down.
The solution to your problem is to define BOOL in your .h like this:
bool mouseIsHeldDown = false;
Then in your mouseDown:
mouseIsHeldDown = true;
And in your mouseUP:
mouseIsHeldDown = false;
Then you can check if mouseIsHeldDown = true in your code.
Hope this problem is fixed!
source to share