How to stop marco with closing file

Hello

I have a problem with macro. I need to check when spreadsheet file is not active, save and close this file. But if I save and close file manually, macro still running and I can not open any file. How to break macro with closing file manually.

Regards

sub Main_share
rem ----------------------------------------------------------------------
rem define variables
dim document   as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document   = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")

rem ----------------------------------------------------------------------
dispatcher.executeDispatch(document, ".uno:Save", "", 0, Array())

rem ----------------------------------------------------------------------
rem dispatcher.executeDispatch(document, ".uno:ShareDocument", "", 1, Array())


end sub


global idleTime
const maxTime = 180

sub start()
  idleTime = 0
  c = thisComponent.CurrentController
  c.addKeyHandler(CreateUnoListener("reset_", "com.sun.star.awt.XKeyHandler") )
  c.addMouseClickHandler(CreateUnoListener("reset_", "com.sun.star.awt.XMouseClickHandler"))
  run_timer(maxTime)
end sub

sub run_timer(dt)
  do
    thisComponent.Sheets.getByIndex(0).getCellbyposition(0,0).Value = dt - idleTime
    idleTime = idleTime + 1
    wait 1000
    if idleTime >= dt then
       Main_share()
       finalize()
       exit do
    end if
  loop while 1
end sub

sub finalize()
  thisComponent.store()
  thisComponent.close(true)
end sub

function reset_keyPressed(event) as boolean
  idleTime = 0
  reset_keyPressed = false
end function

function reset_keyReleased(event) as boolean
  idleTime = 0
  reset_keyReleased = false
end function

function reset_mousePressed(event) as boolean
  idleTime = 0
  reset_mousePressed = false
end function



function reset_mouseReleased(event) as boolean
  idleTime = 0
  reset_mousePressed = false
end function

Where is your reset_disposing? Where are removeKeyHandler and removeMouseClickHandler? How about using OnPrepareUnload?