How to determine the difference between a keyboard event from a keyboard and a generated one?

I set the hook for the keyboard:

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {

Basically, I want to take the taps of the user's keyboard, eat the input, and instead place my own input.

So, if he typed "g", I could send "foo" to the text box.

I am writing in the text box CGEventPost and CGEventSetUnicodeString , as shown here: http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg23343.html

The problem is that each of my programmatically entered characters falls into the hook of the keyboard. Therefore, I cannot return NULL in the keyboard hook to block user input ..., which also blocks all program input!

I distinguished them on the Windows side in C # with the 'injected' flag, see my question a year ago here: How to use low-level 8-bit flags as conventions?

Looking for something similar in Objective-C.

+8
input objective-c keyboard-hook
source share
1 answer

Take a look at the comments in CGEventSource.h. It’s a little easier to move the information together than using the help of the event services . A long but more correct way looks like creating an event source (which obeys the rules of memory management, you need CFRelease it if you finished using it before the program ended):

 myEventSource = CGEventSourceCreate(kCGEventSourceStatePrivate); 

This will create your own event source with a unique identifier; you indicate that the events you created came from there:

 CGEventRef myKeyboardEvent = CGEventCreateKeyboardEvent(myEventSource, keyCode, true); 

When an event arrives, check to see if it happened on your own:

  if( (CGEventGetType(newEvent) == kCGEventKeyDown) && (CGEventGetIntegerValueField(newEvent, kCGEventSourceStateID) == CGEventSourceGetSourceStateID(myEventSource) ) { 

There is also a user data field for the source, which allows you to bypass arbitrary 64 bits if you need to.

A quick and dirty way is to try to select an event field that is unlikely to be a significant value for a keyboard event, for example kCGMouseEventPressure and turn it into a signature:

 CGEventSetIntegerValueField(myKeyboardEvent, kCGMouseEventPressure, 0xFEEDFACE); // The field is an int_64 so you could make the sig longer 
+6
source share

All Articles