英文:
Querying whether a mac is in the locked state using Objective-C
问题
请注意,以下是代码部分的翻译:
CFDictionaryRef session = CGSessionCopyCurrentDictionary();
if (session != NULL) {
d->locked = ![[(id)session objectForKey:(NSString *)kCGSessionOnConsoleKey] boolValue]; // d's locked field name is not yet correct.
CFRelease(session);
}
希望这对您有所帮助。
英文:
I would like to be able detect whether a mac is in the locked or asleep state via Objective-C. This question from 2012 provides half of the answer using the kCGSessionOnConsoleKey
key into the dictionary provided by CGSessionCopyCurrentDictionary()
.
CFDictionaryRef session = CGSessionCopyCurrentDictionary();
if (session != NULL) {
d->locked = ![[(id)session objectForKey:(NSString *)kCGSessionOnConsoleKey] boolValue]; // d's locked field name is not yet correct.
CFRelease(session);
}
The obvious next step of using a CGSSessionScreenIsLocked
key fails because it is not part of the dictionary's entries; TBH it's unclear how the linked answer worked given this, but I've seen many variations on the theme, so I guess it must have at some point.
Was CGSSessionScreenIsLocked
deprecated or does it live somewhere else? Is there an alternative approach to achieve this?
答案1
得分: 0
抱歉,这是您提供的代码,不需要进行翻译。
英文:
Unfortunately the fact that the key is not given under the official documentation page means nothing in the world of Cocoa framework. You can still access the key by specifying it as a raw string (rather than a constant), however be advised that while the screen is not locked, the corresponding value may not be present in the session dictionary. Here is how you may inspect current lock status in the form of a free function:
BOOL isScreenLocked() {
CFDictionaryRef session = CGSessionCopyCurrentDictionary();
const void *value;
if (CFDictionaryGetValueIfPresent(session, CFSTR("CGSSessionScreenIsLocked"), &value)) {
if (((__bridge NSNumber *)value).boolValue) {
return YES;
}
}
return NO;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论