Skip navigation.
 
mlRe: Posting Keyboard Events
FROM : Peter N Lewis
DATE : Sat Sep 06 14:00:02 2008

At 20:15 -0600 5/9/08, Dave DeLong wrote:
>How on earth can I post system keyboard events (without getting a beep)?


As Ken mentioned, first off make sure the key has somewhere to go.

After that, this is roughly the code I use in Keyboard Maestro
(extracted bits and pieces, so it wont compile directly).  My
apologies for the appearance of the code in email, but perhaps it is
still useful.


   verify_noerr( ::CGEnableEventStateCombining( false ) );
   verify_noerr( ::CGSetLocalEventsFilterDuringSuppressionState(
kCGEventFilterMaskPermitAllEvents,
kCGEventSupressionStateSupressionInterval ) );
   verify_noerr( ::CGSetLocalEventsSuppressionInterval( 0.0 ) );

   PostModifierKeys( inModifiers, true );
   verify_noerr( CGPostKeyboardEvent( inChar, inKeyCode, true ) );
   verify_noerr( CGPostKeyboardEvent( inChar, inKeyCode, false ) );
   PostModifierKeys( inModifiers, false );

   verify_noerr( ::CGEnableEventStateCombining( true ) );


with:


void
UCGRemoteControl::PostModifierKeys( const UInt32& inModifiers,
Boolean inKeyDown )
{
   if ( inModifiers&( UInt32(shiftKey) ) ) {
       verify_noerr( ::CGPostKeyboardEvent( (CGCharCode)0,
kCGShiftKeyCode, inKeyDown ) );
   }

   if ( inModifiers&( UInt32(controlKey) ) ) {
       verify_noerr( ::CGPostKeyboardEvent( (CGCharCode)0,
kCGControlKeyCode, inKeyDown ) );
   }
   if ( inModifiers&( UInt32(optionKey)) ) {
       verify_noerr( ::CGPostKeyboardEvent( (CGCharCode)0,
kCGOptionKeyCode, inKeyDown ) );
   }
   if ( inModifiers&( UInt32(cmdKey) ) ) {
       verify_noerr( ::CGPostKeyboardEvent( (CGCharCode)0,
kCGCommandKeyCode, inKeyDown ) );
   }
}

There is an extra piece of code to release the desired key if it is
already down (if the user is pressing the A key already, and you try
to press it again without first releasing it, it wont work).

Also, the key code for A is 0.  6 is Z.

Further, inChar should be lowercase (ie 'a' or 'z').

Enjoy,
    Peter.

--
              Keyboard Maestro 3 Now Available!
                Now With Status Menu triggers!

Keyboard Maestro <http://www.keyboardmaestro.com/> Macros for your Mac
<>          <<A href="http://download.stairways.com/">http://download.stairways.com/>

Related mailsAuthorDate
mlPosting Keyboard Events Dave DeLong Sep 6, 04:15
mlRe: Posting Keyboard Events Ken Thomases Sep 6, 04:56
mlRe: Posting Keyboard Events Dave DeLong Sep 6, 05:51
mlRe: Posting Keyboard Events Peter N Lewis Sep 6, 14:00
mlRe: Posting Keyboard Events Jean-Daniel Dupas Sep 6, 15:50
mlRe: Posting Keyboard Events Dave DeLong Sep 7, 16:34