Querying whether a mac is in the locked state using Objective-C

huangapple go评论56阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月7日 17:26:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定