Share via


IConnectionPoint and .NET or: How I Learned to Stop Worrying and Love Managed Event Sinks (part 1): Sample 1

Sample 1

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Windows.Forms;

using Excel = Microsoft.Office.Interop.Excel;

using Office = Microsoft.Office.Core;

namespace Sample1

{

    internal static class Program

    {

        private static Excel.Application _application;

        private static Excel.Workbook _workbook;

        private static void Main(string[] args)

        {

            _application = new Excel.ApplicationClass();

            _application.Visible = true;

            _workbook = _application.Workbooks.Add(Type.Missing);

            _workbook.BeforeClose += _workbook_BeforeClose;

            _workbook.Close(false, Type.Missing, Type.Missing);

            if (0 == _application.Workbooks.Count)

            {

                Console.WriteLine("Workbook closed.");

                _workbook = null;

            }

            else

            {

                Console.WriteLine("Workbook not closed.");

            }

            if (null != _workbook)

                _workbook.BeforeClose -= _workbook_BeforeClose;

            CleanUp();

        }

        private static void _workbook_BeforeClose(ref bool Cancel)

        {

            Cancel = DialogResult.Yes != MessageBox.Show("Really close?", "Excel", MessageBoxButtons.YesNo);

        }

        private static void CleanUp()

        {

            Console.WriteLine("Cleaning up...");

            if (null != _workbook)

            {

                _workbook.Close(false, Type.Missing, Type.Missing);

                _workbook = null;

            }

            if (null != _application)

            {

                _application.Quit();

                _application = null;

            }

            GC.Collect();

            GC.WaitForPendingFinalizers();

            GC.Collect();

            GC.WaitForPendingFinalizers();

        }

    }

}

Comments