You may try this -
1st you open gpedit.msc, go to Configuration -> Administrative Templates -> System -> Shutdown Options. Now choose Turn off automatic termination of applications that block or cancel shutdown.
And read Microsoft SystemEvents.SessionEnding Event documentation for further development.