Excel automation: Close event missing

前端 未结 4 922
南方客
南方客 2021-01-19 00:56

Another hi all,

I am doing Excel automation via Interop in C#, and I want to be informed when a workbook is closed. However, there is no Close event on the workbook

4条回答
  •  一生所求
    2021-01-19 01:49

    Schedule a SyncContext action on workbook.Deactivate. This event is fired both when the workbook is closed and when another workbook takes focus.

    Normally, in the Deactivate handler you can't check if the workbook is closed or just lost focus, but you can enqueue an action on the SyncContext to execute right after the event. In that action you can check if your workbook is still alive and execute code in case it's not.

    Here's an example:

    // put a syncContext instance somewhere you can reach it
    static SynchronizationContext syncContext = SynchronizationContext.Current ?? new System.Windows.Forms.WindowsFormsSynchronizationContext();
    
    // subscribe to workbook deactivate
    workbook.Deactivate += workbook_Deactivate;
    
    
    [DebuggerHidden]
    private void workbook_Deactivate()
    {
        // here, the workbook is still alive, but we can schedule
        // an action via the SyncContext which will execute 
        // right after the deactivate event is completed. At that 
        // point, the workbook instance (RCW) will no longer be usable
        // meaning that the workbook has been closed
    
        syncContext.Post(x =>
        {
            try
            {
                // will throw if workbook is gone
                workbook.Path.ToString();
            }
            catch
            {
                // handle workbook closed
            }
        }, null);
    }
    

提交回复
热议问题