Getting keyboard type: carbon vs CG

Gerd Knops <[email protected]>
Newsgroups gmane.comp.macosx.devel
Message-ID <[email protected]>
Hi All,

I am trying to wean one of my Cocoa applications of it's last Carbon dependency. In this specific case I need to tell keyboard events from different keyboards apart.

Ideally I could figure out which USB device a keyboard event came from, but that doesn't seem to be within the scope of a Cocoa app.

I settled for the next best thing, which was using the keyboard type.

So I replaced carbon based code (GetEventParameter, kEventParamKeyboardType) with CoreGraphics (CGEventSourceGetKeyboardType).

Problem is the CoreGraphics alternative does not appear to return the correct code. The code is (drop into NSApplication subclass):

- (void)sendEvent:(NSEvent *)anEvent {
	
	NSEventType	type=[anEvent type];
	
	if(type==NSKeyDown || type==NSKeyUp)
	{
		EventRef	ce=(EventRef)[anEvent eventRef];
		
		if(ce)
		{
			unsigned	kbt;
			
			GetEventParameter(
				ce,
				kEventParamKeyboardType,
				typeUInt32, NULL,
				sizeof kbt,
				NULL,
				&kbt
			);
			NSLog(@"kbt (carbon): %d",kbt);
		}
		
		CGEventSourceRef	evSrc=CGEventCreateSourceFromEvent([anEvent CGEvent]);
		
		if(evSrc)
		{
			unsigned	kbt=(NSUInteger)CGEventSourceGetKeyboardType(evSrc);
			
			CFRelease(evSrc);
			
			NSLog(@"kbt (cg): %d",kbt);
		}
	}
	
	[super sendEvent:anEvent];
}

The output for keyboard 1 is:

2009-12-20 13:21:00.827 Anneal[75832:60f] kbt (carbon): 46
2009-12-20 13:21:00.829 Anneal[75832:60f] kbt (cg): 46

And for keyboard 2:

2009-12-20 13:21:04.373 Anneal[75832:60f] kbt (carbon): 204
2009-12-20 13:21:04.374 Anneal[75832:60f] kbt (cg): 46


Any thoughts? Is this a bug in CGEventSourceGetKeyboardType?

Thanks

Gerd
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.