Page 1 of 1

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

Posted: Wed Mar 21, 2018 9:31 am
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!

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

Posted: Wed Mar 21, 2018 2:25 pm
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

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

Posted: Wed Mar 21, 2018 3:49 pm
by Kukulkan
Hello Wilbert,

amazing :shock: Thank you!

I just needed to adapt to my needs. Great!