views:

282

answers:

2

The iPhone app that I released is a wireless game controller, it translates touches on the device into key-presses on the networked Mac. This allowed for playing emulator (e.g. Nestopia) games using the iPhone as a controller. Of course, the day that I released it coincided with an os x update. After installing this update, the simulated key-presses no longer work in Nestopia! The crazier thing is, when I go to 'File > Open' within Nestopia, I can cycle through the file list by hitting the up-arrow on my iphone controller; i.e. the simulated key-presses work in menu items, but not in the game itself. The code that I use to simulate keys is below. Given the list of changes here, can anyone identify which change would cause this problem?

Thanks!!

#define UP  false
#define DOWN true

-(void)sendKey:(CGKeyCode)keycode andKeyDirection:(BOOL)keydirection{
  CGEventRef eventRef = CGEventCreateKeyboardEvent(NULL, keycode, keydirection);
  CGEventPost(kCGSessionEventTap, eventRef);
  CFRelease(eventRef);
}
+1  A: 

I think it's a problem with your code and not with 10.6.3. I have an app I'm writing that simulates key presses, and I've upgraded to 10.6.3, and my simulated key presses still work just fine.

Here's what I'm doing:

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef keyDownPress = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, YES);
CGEventSetFlags(keyDownPress, (CGEventFlags)flags);
CGEventRef keyUpPress = CGEventCreateKeyboardEvent(source, (CGKeyCode)keyCode, NO);

CGEventPost(kCGAnnotatedSessionEventTap, keyDownPress);
CGEventPost(kCGAnnotatedSessionEventTap, keyUpPress);

CFRelease(keyDownPress);
CFRelease(keyUpPress);
CFRelease(source);
Dave DeLong
Thanks, but alas, no luck. Just to reiterate, the code that I posted (and yours as well!) do simulate key presses in 10.6.3; I can still play flash games, control web pages, etc. The problem is specific to the simulated key presses reaching Nestopia. In all other versions of 10.5 and 10.6, the simulated key presses control Nestopia as expected. But in 10.6.3, it is as if they never occur.
Lou Z.
+1  A: 

The author of Mac Nestopia is using an older call, GetKeys(), to capture key events. As of 10.6.3, GetKeys does not catch generated key presses using the methods detailed in this post. The workaround I found was to use this instead:

-(void)sendKey:(CGKeyCode)keycode andKeyDirection:(BOOL)keydirection{
  AXUIElementRef axSystemWideElement = AXUIElementCreateSystemWide();
  AXError err = AXUIElementPostKeyboardEvent(axSystemWideElement, 0, keycode, keydirection);
  if (err != kAXErrorSuccess)
    NSLog(@" Did not post key press!");
}

Huge thanks to Richard Bannister for his quick email responses!

Lou Z.