Gettings objects by name

Top  Previous  Next

When you create complex parts and assemblies it is best to name them with other than the default names. That way you can get hold of them in your program without having to remember indices into a get_Item array, or having to remember that WorkPoint1 is the point at the end of the tube or that WorkPlane3 is in the center of the cube.

 

(Note that for international programs you may prefer to use indices, because the standard objects created by Inventor change the names. For example "X Axis" in English is "Asse X" in Italian.)

 

Here are some functions for getting hold of named objects:

 

bool GetSketchInPartByName (CComPtr<PlanarSketch>& pSketch, // return value if sketch found

                           const wchar_t* const pszSketchName,

                           CComPtr<PartComponentDefinition>& pPartCompDef,

                           const bool kbShowErr /*=true*/)

{

   // Get the sketch in the part by name...

   HRESULT hRes = pPartCompDef->Sketches->get_Item(CComVariant(pszSketchName), &pSketch);

   if (FAILED(hRes)) {

       if (kbShowErr) {

           ShowCOMError (hRes,L"GetSketchByName(%s) but could not 'get' sketch\n",pszSketchName);

       }

       return false ;

 

   } else {

       return true ;

   }

}

 

 

HRESULT GetWorkPlaneByName (CComPtr<WorkPlane>& pWorkPlane,

                           const wchar_t* const pszWorkPlaneName,

                           CComPtr<PartComponentDefinition>& pPartCompDef)

{

   // Get the sketch in the part by name...

   HRESULT hRes = pPartCompDef->WorkPlanes->get_Item(CComVariant(pszWorkPlaneName), &pWorkPlane);

   if (FAILED(hRes) || (pWorkPlane == nullptr)) {

       ShowCOMError (hRes,L"GetWorkPlaneByName but  'get' failed\n");

       return (E_FAIL) ;

   }

 

   return (S_OK) ;

}

 

HRESULT GetWorkAxisByName (CComPtr<WorkAxis>& pWorkAxis,

                          const wchar_t* const pszWorkAxisName,

                          CComPtr<PartComponentDefinition>& pPartCompDef)

{

   // Get the sketch in the part by name...

   HRESULT hRes = pPartCompDef->WorkAxes->get_Item(CComVariant(pszWorkAxisName), &pWorkAxis);

   if (FAILED(hRes) || (pWorkAxis == nullptr)) {

       ShowCOMError (hRes,L"GetWorkAxisByName but  'get' failed\n");

       return (E_FAIL) ;

   }

 

   return (S_OK) ;

}

 

You can imagine what GetWorkPointByName will look like.

 

Since these functions report errors you could ignore their return values if you want, if there is an error you'll see it.

 

 

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