2009-08-24 5 views
5

私はMac用のC(Leopard)のアプリケーションを作成しています。スリープ、起床、シャットダウン、再起動。ログイン時に起動エージェントとしてlaunchdを実行し、通知の監視を開始します。次のように私はこれを行うために使用しているコードは次のとおりです。ただしMac OSXで電力通知(特にシャットダウン)を受け取る

/* ask for power notifications */ 
static void StartPowerNotification(void) 
{ 
    static io_connect_t rootPort; 
    IONotificationPortRef notificationPort; 
    io_object_t notifier; 

    rootPort = IORegisterForSystemPower(&rootPort, &notificationPort, 
             PowerCallback, &notifier); 
    if (!rootPort) 
     exit (1); 

    CFRunLoopAddSource (CFRunLoopGetCurrent(), 
         IONotificationPortGetRunLoopSource(notificationPort), 
         kCFRunLoopDefaultMode); 
} 

/* perform actions on receipt of power notifications */ 
void PowerCallback (void *rootPort, io_service_t y, 
        natural_t msgType, void *msgArgument) 
{ 
    switch (msgType) 
    { 
     case kIOMessageSystemWillSleep: 
      /* perform sleep actions */ 
      break; 

     case kIOMessageSystemHasPoweredOn: 
      /* perform wakeup actions */ 
      break; 

     case kIOMessageSystemWillRestart: 
      /* perform restart actions */ 
      break; 

     case kIOMessageSystemWillPowerOff: 
      /* perform shutdown actions */ 
      break; 
    } 
} 

、睡眠と覚醒(kIOMessageSystemWillSleepkIOMessageSystemHasPoweredOn)のための唯一の上位2 これまでが呼び出されます。私は再起動やシャットダウン(kIOMessageSystemWillRestartkIOMessageSystemWillPowerOff)の通知を得ることはありません。

何か間違っていますか?または、私に再起動とシャットダウンの通知を与える別のAPIがありますか?私はそれをCプログラム(私がよく知っているもの)として保つことを好むでしょうが、選択肢の賢明な提案に開放しています(私はログイン/ログアウトフックを見てきましたが、これらは廃止されているようですlaunchdの)

ご協力いただきありがとうございます!

答えて

4

NSWorkspaceからNSWorkspaceWillPowerOffNotification通知を登録することができます。これはC関数ではなく動作します。

WorkspaceResponder.mで次に
#import <AppKit/AppKit.h> 
#import "WorkspaceResponder.h" 

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter]; 
    WorkspaceResponder *mainController = [[WorkspaceResponder alloc] init]; 

    //register for shutdown notications 
    [nc addObserver:mainController 
selector:@selector(computerWillShutDownNotification:) 
      name:NSWorkspaceWillPowerOffNotification object:nil]; 
    [[NSRunLoop currentRunLoop] run]; 
    [pool release]; 
    return 0; 
} 

- (void) computerWillShutDownNotification:(NSNotification *)notification { 
    NSLog(@"Received Shutdown Notification"); 
} 
+0

ありがとうございました!これらの通知を受け取るためにウィンドウまたはドックアイコンが必要かどうか知っていますか? – binarybob

+1

いいえ、そうではありません。サンプルコードを追加しました。 –

+0

もう一度、Robに感謝します。 – binarybob

0

IORegisterForSystemPowerを使用すると、あなたが求めるイベントを提供しません。関数ドキュメントからの引用:

/*! @function IORegisterForSystemPower

@abstractシステムのスリープ&ウェイク通知を受信する目的で、コール元をルートパワードメインIOService に接続します。

システムシャットダウンと再起動通知は提供されません。

関連する問題