Detect mouse being held down

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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

回答1:

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


回答2:

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.



回答3:

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!



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