Suggestion :- try reading docs of Ps and Flex ...not sure but u may find it there....!!!
I'm doing something similar for InDesign, I haven't tested it on Photoshop, but it should look something like :
and then define the applicationClosingHandler function to preform the action you want.
See the events references here : Photoshop event codes
And documentation about Using the host adapter libraries
Hope it helps.Cheers.