In my Mac application I am trying to intercept right mouse down/up events using CG Event Taps. I have the code that is registering as a listener working just fine. What I am trying to do is intercept when the user clicks down with the right mouse button, and eat the event temporarily. When they let go of the right mouse button I want to post a right mouse down event if they haven't moved the mouse since the original mouse down event. If they have moved the mouse I want my app's code to do something different. This all works great if I run the code on my Macbook using the trackpad. However, when I plug a mouse into the same computer every other mouse down event does not trigger my callback.
The basic logic for doing this is I keep track of an "ignore next event" bool. When my program first runs this is set to false. When I get a right mouse down event I return NULL. When the right mouse up event triggers I create and post a new right mouse down event with ignoreNext to true. I then return the right mouse up event.
Here is my code:
CGPoint mouseDownPoint;
bool ignoreNext;
//---------------------------------------------------------------------------
CGEventRef MouseTapCallback( CGEventTapProxy aP开发者_运维问答roxy, CGEventType aType, CGEventRef aEvent, void* aRefcon )
//---------------------------------------------------------------------------
{
if( aType == kCGEventRightMouseDown ) NSLog( @"down" );
else if( aType == kCGEventRightMouseUp ) NSLog( @"up" );
else NSLog( @"other" );
NSLog( @"ignored: %d", ignoreNext );
CGPoint theLocation = CGEventGetLocation(aEvent);
if( !ignoreNext )
{
if( aType == kCGEventRightMouseDown )
{
mouseDownPoint = theLocation;
return NULL;
}
else if( aType == kCGEventRightMouseUp )
{
if( abs( theLocation.x - mouseDownPoint.x ) < 1 &&
abs( theLocation.y - mouseDownPoint.y ) < 1 )
{
ignoreNext = true;
CGEventRef theNewEvent = CGEventCreateMouseEvent( NULL,
kCGEventRightMouseDown,
mouseDownPoint,
kCGMouseButtonRight );
CGEventSetType( theNewEvent, kCGEventRightMouseDown );
CGEventPost( kCGHIDEventTap, theNewEvent );
return aEvent;
}
else
{
// execute my app's code here...
return NULL;
}
}
}
ignoreNext = false;
return aEvent;
}
The output for this when I test it with the track pad is (working correctly):
down ignored: 0 up ignored: 0 down ignored: 1
The output for this when I test it with an actual mouse (note: the mouse down event is missing on the second run through):
First time clicking down then up...
down ignored: 0 up ignored: 0 down ignored: 1
Second time, the mouse down event doesn't trigger my callback...
up ignored: 0
Has anyone seen anything like this before, and if so, what did you do to solve this problem? Thanks for your time.
精彩评论