[done] How to detect Mac power off / log off?

Mac OSX specific forum
User avatar
Kukulkan
Addict
Addict
Posts: 1352
Joined: Mon Jun 06, 2005 2:35 pm
Location: germany
Contact:

[done] How to detect Mac power off / log off?

Post by Kukulkan »

Hi,

my app does not quit if Window close is hit. It just minimizes to the tray (if user like it like that). But now, if system is shut down or logged out, my app is preventing MacOS from shutting down and the user first has to close my app.

Is there a valid way to detect if there is a system shutdown? So I can close my app due to this event?

I found this StackOverflow article, but sadly I'm not able to translate this to PureBasic (I'm not a regular MacOS developer). Is there someone who already did something like this before?

Thanks!
Last edited by Kukulkan on Wed Mar 21, 2018 3:49 pm, edited 1 time in total.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: How to detect Mac power off / log off?

Post by wilbert »

Code: Select all

Enumeration #PB_Event_FirstCustomValue
  #EventPowerOff
EndEnumeration

ProcedureC MyPowerOffNotification(obj, sel, notification)
  PostEvent(#EventPowerOff)
EndProcedure

Procedure AddPowerOffCallback()
  Protected class = objc_allocateClassPair_(objc_getClass_("NSObject"), "MyPowerOffNotificationClass", 0)
  Protected sel = sel_registerName_("MyPowerOffNotification:")
  class_addMethod_(class, sel, @MyPowerOffNotification(), "v@:@")
  objc_registerClassPair_(class)
  CocoaMessage(0, CocoaMessage(0, CocoaMessage(0, 0, "NSWorkspace sharedWorkspace"), "notificationCenter"), 
               "addObserver:", CocoaMessage(0, class, "new"), "selector:", sel, "name:$", 
               @"NSWorkspaceWillPowerOffNotification", "object:", #nil)
EndProcedure

AddPowerOffCallback()



; *** main code ***

OpenWindow(0, 0, 0, 320, 84, "Power off demo", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)

Repeat
  Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow Or Event = #EventPowerOff
Windows (x64)
Raspberry Pi OS (Arm64)
User avatar
Kukulkan
Addict
Addict
Posts: 1352
Joined: Mon Jun 06, 2005 2:35 pm
Location: germany
Contact:

Re: How to detect Mac power off / log off?

Post by Kukulkan »

Hello Wilbert,

amazing :shock: Thank you!

I just needed to adapt to my needs. Great!
Post Reply