Can't unsubscribe from the event in Revit

I’m trying to set up the UI to automatically clear elements when I subscribe to an event DialogBoxShowing. I can’t unsubscribe from it and the replacement of user actions continues even when the code isn’t executing.

I don’t have enough experience to find the error. Maybe someone has encountered this. Thank you in advance!

def call_purge():

    def import_replacement(sender, args):

        print('5')
        print(type(args))

        if args.DialogId == 'Dialog_Revit_PurgeUnusedTree':
                args.OverrideResult(1)

    """Call Revit "Purge Unused" after completion."""
    # commandId = \
    #     UI.RevitCommandId.LookupPostableCommandId(
    #         UI.PostableCommand.PurgeUnused
    #         )

    commandId = UI.RevitCommandId.LookupCommandId("ID_PURGE_UNUSED")


    try:
        __revit__.DialogBoxShowing += framework.EventHandler[UI.Events.DialogBoxShowingEventArgs](import_replacement)
        __revit__.PostCommand(commandId)
        __revit__.DialogBoxShowing -= framework.EventHandler[UI.Events.DialogBoxShowingEventArgs](import_replacement) 
    except:
        print(traceback.format_exc())

        
if __name__ == '__main__':
    call_purge()
    print('-' * 50)
    print('Script is finished.')
1 Like

@Mi-liali

Hi, Andreas!

Thanks for the suggested option.
But how can I disable my hook, when I’m not working with my application?

1 Like

@Mi-liali

# Imports
from pyrevit import revit, EXEC_PARAMS
from Autodesk.Revit.UI import TaskDialog

# Variables
doc   = revit.doc

# Main
if not doc.IsFamilyDocument:
    TaskDialog.Show("Warnung", r"Link CAD, don't import.")
    EXEC_PARAMS.event_args.Cancel = True # Stop Execution

else:
    TaskDialog.Show("Success", r"Family Import is allowed!")

i have just an example where the hook is driven by a if-statement

1 Like