gpt4 book ai didi

c - 在 Mac OSX 上接收电源通知(尤其是关机)

转载 作者:太空狗 更新时间:2023-10-29 17:03:05 24 4
gpt4 key购买 nike

我正在用 C 为 Mac (Leopard) 编写一个应用程序,它需要在接收电源通知时做一些工作,例如 sleep 、唤醒、关机、重启。它通过 launchd 作为登录时的启动代理运行,然后开始监视通知。我用来执行此操作的代码如下:

/* 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;
}
}

但是,只有 sleep 和唤醒的前两个(kIOMessageSystemWillSleepkIOMessageSystemHasPoweredOn)曾经 被调用。我从未收到任何重启或关机通知(kIOMessageSystemWillRestartkIOMessageSystemWillPowerOff)。

我做错了什么吗?或者是否有另一个 API 可以给我重启和关机通知?我更愿意将它保留为 C 程序(因为那是我所熟悉的),但愿意接受任何明智的替代建议(我已经看过登录/注销 Hook ,但这些似乎已被弃用的发射)。

在此先感谢您的帮助/提示!

最佳答案

我知道您可以从 NSWorkspace 注册 NSWorkspaceWillPowerOffNotification 通知,这不是 C 函数但确实有效。

#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;
}

然后在 WorkspaceResponder.m 中:

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

关于c - 在 Mac OSX 上接收电源通知(尤其是关机),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1321219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com