1

The code below clicks the mouse, but (I think) doesn't unclick the mouse. I have to manually click the correct mouse button, then click again, and then it gets "unstuck".

And the two commented lines in the main function, for middle clicking or double-clicking, don't work either.

One-liner that reproduces issue:

echo '
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
#import <Foundation/Foundation.h>


void clickMouse(CGEventType mouseDown, CGEventType mouseUp, CGMouseButton mouseButton, UInt32 clickCount, CGEventFlags modifiers) {

  // current mouse position
  CGPoint mousePosition = CGEventGetLocation(CGEventCreate(NULL));

  // because?
  CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  CGEventRef eventDown = CGEventCreateMouseEvent(source, mouseDown, mousePosition, mouseButton);
  CGEventRef eventUp   = CGEventCreateMouseEvent(source, mouseUp,   mousePosition, mouseButton);

  // necessary?
  CGEventSetType(eventDown, mouseDown);
  CGEventSetType(eventUp,   mouseUp);

  CGEventSetFlags(eventDown, modifiers);

  CGEventSetIntegerValueField(eventDown, kCGMouseEventClickState, clickCount);
  CGEventSetIntegerValueField(eventUp,   kCGMouseEventClickState, 0);

  CGEventPost(kCGHIDEventTap, eventDown);
  CGEventPost(kCGHIDEventTap, eventUp); // error here?

}

int main(int argc, char** argv)
{

  @autoreleasepool {
    clickMouse(kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGMouseButtonLeft, 1, 0);
  //clickMouse(kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGMouseButtonLeft, 2, 0);
  //clickMouse(kCGEventOtherMouseDown, kCGEventOtherMouseUp, kCGMouseButtonCenter, 1, 0);
  }

  return 0;
}

' > issue.m; gcc -ObjC -framework Cocoa  -o ./issue issue.m; ./issue
#

I am on:

$ sw_vers
ProductVersion: 10.9.5

Related:

Community
  • 1
  • 1
sam boosalis
  • 1,997
  • 4
  • 20
  • 32
  • Why are you using different values for `kCGMouseEventClickState` for the down vs. the up event? – Ken Thomases Oct 22 '14 at 05:41
  • One of the linked answers recommended it. I had tried both different and the same. – sam boosalis Oct 22 '14 at 07:07
  • @samboosalis : try using a `modifiers=kCGEventFlagMaskShift ` ... `CGEventSetFlags(eventDown, modifiers);` .. it work for me .. – rahul_send89 Oct 23 '14 at 05:54
  • @rahul_send89 I already have that line in the code. And there is an issue even without modifiers. Did you copy and paste the one-liner into your terminal, and it didn't get stuck? – sam boosalis Oct 23 '14 at 06:07

0 Answers0