Starting Inventor in C#

Top  Previous  Next

The first thing to do is to make sure you can access Inventor using C#. You have to ad a reference to the Inventor API like so:

 

C-INV

Note that you need to choose the .NET Framework, else GetActiveObject will not be found in Marshal:

 

Framework-Marshall

 

 

In VS2019 the sequence is this:

 

Browse-for-reference

 

 

Then you can use the following code to get you going...

 

// CInventor starts up and closes down Inventor

// 2019-07-02 : Started.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Runtime.InteropServices;

using System.Windows.Forms;

using System.Diagnostics;

 

namespace SAClassif

{

   static class CInventor

   {

       private static Inventor.Application m_Inventor;

       private static bool m_bWasAlreadyRunning = false;

 

       public static bool ConnectToInventor ()

       {

           Debug.WriteLine("Connecting to inventor...");

           try

           {

               // See if Inventor is already running...

               m_Inventor = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application");

               m_bWasAlreadyRunning = true;

               Debug.WriteLine("Inventor already running...");

           }

           catch (Exception ex1)

           {

               Debug.WriteLine("Not running, will start it...");

               m_bWasAlreadyRunning = false;

               try

               {

                   Type invAppType = Type.GetTypeFromProgID("Inventor.Application");

                   m_Inventor = (Inventor.Application)System.Activator.CreateInstance(invAppType);

                   m_Inventor.Visible = true;

                   Debug.WriteLine("Started Inventor");

               }

               catch (Exception ex2)

               {

                   MessageBox.Show(ex2.ToString());

                   MessageBox.Show("Unable to start Inventor");

                   return false;

               }

           }

 

           return m_Inventor != null;

       }

 

       public static void DisconnectFromInventor()

       {

           if (m_Inventor == null)

           {

               return;

           }

 

           if (m_bWasAlreadyRunning)

           {

               // I did not start Inventro so I shoulkd not close it...

               return;

           }

 

           // Inventor was not running, you started it so you should shut it down

           m_Inventor.Quit();

           m_Inventor = null;

       }

   }

}

 

 

Text, images and diagrams © 2021 Owen F. Ransen. All rights reserved. (But copy the source code as much as you want!)