Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7681761
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T18:24:54+00:00 2026-05-31T18:24:54+00:00

I have a c# method in console app X this starts a process; console

  • 0

I have a c# method in console app X this starts a process; console app Y (written in the same c# solution).
App Y then fires a vba macro in an Excel 2010 workbook.

For testing purposes in the wkbook VBA I’ve added some code to force a runtime error 1004.

The winForm uses a process event, triggered using a Forms timer, to kill the Process. It is working as programmed I’d just like to try to make it do a little more.
Why, when I kill the process, is the instance of XL staying open at the point when it finds the error? How do I find a way of getting rid of the instance of XL, if it still exists, when it kills the process, and then posting an error message back to my winForm?

(ps the following code is familiar but the question is not a duplicate)

    private int elapsedTime;
    private Process p;
    private System.Windows.Forms.Timer myTimer;
    const int SLEEP_AMOUNT = 1000;//1s
    const int MAXIMUM_EXECUTION_TIME = 5000;//5s


    private void btRunReport_Click(object sender, EventArgs e) {
        btRunReport.Enabled = false;
        lbStatusUpdate.Text = "Processing..";

        //instantiate a new process and set up an event for when it exits
        p = new Process();
        p.Exited += new EventHandler(MyProcessExited);
        p.EnableRaisingEvents = true;
        p.SynchronizingObject = this;
        elapsedTime = 0;
        this.RunReportScheduler();

        //add in a forms timer so that the process can be killed after a certain amount of time
        myTimer = new System.Windows.Forms.Timer();
        myTimer.Interval = SLEEP_AMOUNT;
        myTimer.Tick += new EventHandler(TimerTickEvent);
        myTimer.Start();

    }
    private void RunReportScheduler() {
        p.StartInfo.FileName = @"\\fileserve\department$\ReportScheduler_v3.exe";
        p.StartInfo.Arguments = 2;
        p.Start();
    }
    private void MyProcessExited(Object source, EventArgs e){
        myTimer.Stop();
        btRunReport.Enabled = true;
        lbStatusUpdate.Text = "Start";
    }
    void TimerTickEvent(Object myObject, EventArgs myEventArgs) {
        myTimer.Stop();
        elapsedTime += SLEEP_AMOUNT;
        if (elapsedTime > MAXIMUM_EXECUTION_TIME)
        {p.Kill();}
        else
        {myTimer.Start();}
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T18:24:55+00:00Added an answer on May 31, 2026 at 6:24 pm

    I’ve left the original bit of code unchanged but I’ve used the help from Andrew but mainly the help of a good friend of mine who unfortunately isn’t signed up to SO. Excel seems to be dead!. Plus he’s coded it in such a way that it passes back an indicator telling the form if it had problems with excel or not. Also gives us the option of building in maximum run times for each excel process.

    He used the following SO answer to help get rid of Excel

    1.In scheduler program

    • Move timer there
    • Implement excel cleaning code in the case there is no errors in vba and in the opposite case when maximum execution time reached (use Kill method)
    • From the scheduler return 0 to the forms application if excel finished normally or 1 if it was killed

    2.In the forms application analyse return value from the scheduler in the ProcessExited event handler and enable button, etc

    So, the new scheduler:

     using System;
     using System.Text;
     using System.Runtime.InteropServices;
     using System.Diagnostics;
     using Excel = Microsoft.Office.Interop.Excel;
     using System.Timers;
    
    
    class Program
    {
       private const int SLEEP_AMOUNT = 1000;
       private const int MAXIMUM_EXECUTION_TIME = 10000;
       private Excel.Application excelApp =null;
       private Excel.Workbook book =null;
       private Timer myTimer;
       private int elapsedTime;
       private int exitCode=0;
    
       [DllImport("user32.dll", SetLastError =true)]
       static extern uint GetWindowThreadProcessId(IntPtr hWnd,out uint lpdwProcessId);
    
       static int Main(string[] args)
        {
           Program myProgram = newProgram();
           myProgram.RunExcelReporting(1);
           return myProgram.exitCode;
        }
    
    
       void myTimer_Elapsed(object sender,ElapsedEventArgs e)
        {
           myTimer.Stop();
           elapsedTime += SLEEP_AMOUNT;
           if (elapsedTime > MAXIMUM_EXECUTION_TIME)
            {
                //error in vba or maximum time reached. abort excel and return 1 to the calling windows forms application
               GC.Collect();
               GC.WaitForPendingFinalizers();
               if (book != null)
                {
                   book.Close(false,Type.Missing, Type.Missing);
                   Marshal.FinalReleaseComObject(book);
                   book =null;
                }
    
               if (excelApp != null)
                {
                   int hWnd = excelApp.Hwnd;
                   uint processID;
                   GetWindowThreadProcessId((IntPtr)hWnd,out processID);
                   if (processID != 0)
                       Process.GetProcessById((int)processID).Kill();
                    excelApp =null;
                    exitCode = 1;
                }
            }
           else
            {
                myTimer.Start();
            }
        }
    
    
       void RunExcelReporting(int x)
        {
            myTimer =new Timer(SLEEP_AMOUNT);
            elapsedTime = 0;
            myTimer.Elapsed +=new ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Start();
    
           try{
                excelApp =new Excel.Application();
                excelApp.Visible =true;
                book = excelApp.Workbooks.Open(@"c:\jsauto.xlsm");
                excelApp.Run("ThisWorkbook.rr");
                book.Close(false,Type.Missing, Type.Missing);
            }
            catch (Exception ex){
               Console.WriteLine(ex.ToString());
            }
    
           finally
            {
               //no error in vba and maximum time is not reached. clear excel normally
               GC.Collect();
               GC.WaitForPendingFinalizers();
    
               if (book != null)
                {
                   try {
                        book.Close(false,Type.Missing, Type.Missing);
                    }
                    catch { }
                   Marshal.FinalReleaseComObject(book);
                }
    
               if (excelApp != null)
                {
                   excelApp.Quit();
                   Marshal.FinalReleaseComObject(excelApp);
                   excelApp =null;
                }
            }
        }
    }
    

    And the new forms application:

    public partial class Form1 : Form
    
    {
       SqlDataAdapter myAdapt = null; 
       DataSet mySet =null; 
       DataTable myTable =null; 
    
       public Form1()
        { InitializeComponent();}
    
        privatevoid Form1_Load(object sender,EventArgs e){ 
            InitializeGridView();
        }
    
       private Process myProcess;
    
       private void btRunProcessAndRefresh_Click(object sender,EventArgs e)
        {
            myProcess =new Process();
            myProcess.StartInfo.FileName =@"c:\VS2010Projects\ConsoleApplication2\ConsoleApplication4\bin\Debug\ConsoleApplication4.exe";
            myProcess.Exited +=new EventHandler(MyProcessExited);
            myProcess.EnableRaisingEvents =true;
            myProcess.SynchronizingObject =this;
            btRunProcessAndRefresh.Enabled =false;
            myProcess.Start();
        }
    
        privatevoid MyProcessExited(Object source,EventArgs e)
        {
            InitializeGridView();
            btRunProcessAndRefresh.Enabled =true;
           if (((Process)source).ExitCode == 1)
            {
               MessageBox.Show("Excel was aborted");
            }
           else
            {
               MessageBox.Show("Excel finished normally");
            }
        }
    
       private void btnALWAYSWORKS_Click(object sender,EventArgs e) { 
            InitializeGridView();
        }
    
        privatevoid InitializeGridView() { 
          using (SqlConnection conn =new SqlConnection(@"Data Source=sqliom3;Integrated Security=SSPI;Initial Catalog=CCL"))
            {
            myAdapt =new SqlDataAdapter("SELECT convert(varchar(25),getdate(),120) CurrentDate", conn);
            mySet =new DataSet();
            myAdapt.Fill(mySet,"AvailableValues"); 
            myTable = mySet.Tables["AvailableValues"];
    
            this.dataGridViewControlTable.DataSource = myTable;
            this.dataGridViewControlTable.AllowUserToOrderColumns =true;
            this.dataGridViewControlTable.Refresh();
            }
        }
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have a method that creates a Process calling a console app. double myProcess()
I have a small console app containing a web server written in c#. When
I have a console app, the central process of which is to get the
I have written software (C#. NET console app) to run on all of our
I have created a console application that calls a method on a webservice. I
I have a console application which is parsing HTML documents via the WebRequest method
I have this method on a webpart: private IFilterData _filterData = null; [ConnectionConsumer(Filter Data
I'm trying to iterate through the referenced assemblies in my console app. I have
I have setup a test database and console app to confirm the following: Given
I've console app. written in Delphi 2010. It's output is Unicode supported. (I used

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.