Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

cocoa - Lock screen by API in macOS

Is there an API, that can lock the screen as the menu bar entry you can add from Keychain preferences?

This Keychain function is (was) locking the screen but not bringing the system to sleep.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not officially documented and uses private API, but the following works on MacOS 10.10 (and maybe also on earlier systems):

// lockscreen.c
extern int SACLockScreenImmediate ( void );

int main ( ) {
    return SACLockScreenImmediate();
}

Build with:

clang -F /System/Library/PrivateFrameworks -framework login -o lockscreen lockscreen.c 

Now calling ./lockscreen will lock the screen immediately, regardless what the user has configured in their security preferences (whether to lock on screensaver/system sleep) and without logging the user out. This is the function the system uses internally for locking the screen.

I strongly discourage using it, it may break your app and I'm not even sure I am calling it correctly (maybe it needs arguments, maybe it has a return value), so it may even break your whole system (temporarily - reboot will fix everything), who knows. I just wanted to post that somewhere for documentation.

If someone with better hacker skills than me can analyze this call some more, this would be nice and useful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...