My original answer would only work if the window was active. I also wanted it to work when the window was hidden, and came up with the code below.
This works for ordinary keys (Enter, Space, arrow keys, etc.). It uses keycodes so it won't work for letters and symbols that might move around based on the user's language and region.
And it doesn't handle modifier keys like Command. If someone can figure that out I will gladly give them credit for the answer to this question.
// For Safari 4.x+
if ([[flashView className] isEqual:@"WebHostedNetscapePluginView"])
{
CGEventRef event = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keycode, true);
[flashView keyDown:[NSEvent eventWithCGEvent:event]];
CFRelease(event);
}
else
{
EventRecord event;
event.what = keyDown;
event.message = keycode << 8;
event.modifiers = 0;
// For Safari 3.x
if ([flashView respondsToSelector:@selector(sendEvent:)]) {
[(id)flashView sendEvent:(NSEvent*)&event];
event.what = keyUp;
[(id)flashView sendEvent:(NSEvent*)&event];
}
// For Safari 4.x
else if ([(id)flashView respondsToSelector:@selector(sendEvent:isDrawRect:)]) {
[(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
event.what = keyUp;
[(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
}
else
{
NSLog(@"ERROR: unable to locate event selector for Flash plugin");
}
}
You must first locate the Flash widget in the browser; pass your WebView to this.
- (NSView*)_findFlashViewInView:(NSView*)view
{
NSString* className = [view className];
// WebHostedNetscapePluginView showed up in Safari 4.x,
// WebNetscapePluginDocumentView is Safari 3.x.
if ([className isEqual:@"WebHostedNetscapePluginView"] ||
[className isEqual:@"WebNetscapePluginDocumentView"])
{
// Do any checks to make sure you've got the right player
return view;
}
// Okay, this view isn't a plugin, keep going
for (NSView* subview in [view subviews])
{
NSView* result = [self _findFlashViewInView:subview];
if (result) return result;
}
return nil;
}