3

我有一个可以在 OSX 下改变音量的应用程序。它缺少的是按下声音上/下键时提供的视觉反馈。有谁知道如何以编程方式调用该行为?谢谢

4

2 回答 2

6

这是 George Warner 和 Casey Fleser 的一个小代码,可以做到这一点。仔细想想,这确实是你想做的事情。

// Save as sound_up.m
// Compile: gcc -o sound_up sound_up.m -framework IOKit -framework Cocoa

#import <Cocoa/Cocoa.h>
#import <IOKit/hidsystem/IOHIDLib.h>
#import <IOKit/hidsystem/ev_keymap.h>


static io_connect_t get_event_driver(void)
{
    static  mach_port_t sEventDrvrRef = 0;
    mach_port_t masterPort, service, iter;
    kern_return_t    kr;

    if (!sEventDrvrRef)
    {
        // Get master device port
        kr = IOMasterPort( bootstrap_port, &masterPort );
        check( KERN_SUCCESS == kr);

        kr = IOServiceGetMatchingServices( masterPort, IOServiceMatching( kIOHIDSystemClass ), &iter );
        check( KERN_SUCCESS == kr);

        service = IOIteratorNext( iter );
        check( service );

        kr = IOServiceOpen( service, mach_task_self(),
                            kIOHIDParamConnectType, &sEventDrvrRef );
        check( KERN_SUCCESS == kr );

        IOObjectRelease( service );
        IOObjectRelease( iter );
    }
    return sEventDrvrRef;
}


static void HIDPostAuxKey( const UInt8 auxKeyCode )
{
  NXEventData   event;
  kern_return_t kr;
  IOGPoint      loc = { 0, 0 };

  // Key press event
  UInt32      evtInfo = auxKeyCode << 16 | NX_KEYDOWN << 8;
  bzero(&event, sizeof(NXEventData));
  event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
  event.compound.misc.L[0] = evtInfo;
  kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
  check( KERN_SUCCESS == kr );

  // Key release event
  evtInfo = auxKeyCode << 16 | NX_KEYUP << 8;
  bzero(&event, sizeof(NXEventData));
  event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
  event.compound.misc.L[0] = evtInfo;
  kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
  check( KERN_SUCCESS == kr );

}

int main(int argc, char *argv[]) {
  HIDPostAuxKey(NX_KEYTYPE_SOUND_UP);
}

其他有趣的键码包括:NX_KEYTYPE_SOUND_DOWN, NX_KEYTYPE_MUTE, NX_KEYTYPE_PLAY.

于 2012-05-09T16:55:28.527 回答
0

我将通过模拟向上/向下音量键的物理按下来实现这一点,并让操作系统处理细节。也许用户禁用了视觉反馈,也许它发生了变化,等等——这是最安全的方法。

看看这个:Simulating key press events in Mac OS X

于 2012-04-23T00:46:51.893 回答