Beispiel #1
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            disposed = true;
            if (disposing && started)
            {
                int count = workbooks.Count;
                for (int i = 0; i < count; i++)
                {
                    workbooks[0].Close(false);
                }

                workbooks = null;
                excelProcess.Dispose();
            }

            if (started)
            {
                Marshal.ReleaseComObject(_workbooks);
                _workbooks = null;
                Process process = null;
                try
                {
                    var hWnd = (IntPtr)_excel.Hwnd;
                    process = ProcessFunctions.GetProcessByHwnd(hWnd);
                    _excel.DisplayAlerts        = true;
                    _excel.IgnoreRemoteRequests = false;
                    _excel.Quit();
                    Marshal.ReleaseComObject(_excel);
                    _excel = null;
                    process.WaitForExit(1000);
                }
                catch
                {
                }
                finally
                {
                    if (process != null && !process.HasExited)
                    {
                        ProcessFunctions.TryKillProcess(process);
                    }

                    process?.Dispose();
                }
            }
        }
Beispiel #2
0
        public void Start(bool visible, bool displayAlerts, bool ignoreRemoteRequests)
        {
            AssertNotDisposed();
            if (started)
            {
                return;
            }

            try
            {
                _excel = new Excel.Application();
            }
            catch (Exception e)
            {
                throw new Exception("Failed to start Excel.", e);
            }

            var  hWnd = (IntPtr)_excel.Hwnd;
            uint processId;

            ProcessFunctions.GetWindowThreadProcessId(hWnd, out processId);
            excelProcess = Process.GetProcessById((int)processId);
            excelProcess.EnableRaisingEvents = true;
            excelProcess.Exited += (s, e) =>
            {
                if (!disposed)
                {
                    Dispose(true);
                    OnExit(ExitCause.Unknown);
                }
            };

            _excel.Visible              = true;
            _excel.DisplayAlerts        = displayAlerts;
            _excel.IgnoreRemoteRequests = ignoreRemoteRequests;

            _workbooks      = _excel.Workbooks;
            workbooks       = new List <IWorkbook>();
            disposeCallback = sender => workbooks.Remove((Workbook)sender);
            started         = true;
        }