Skip to main content

ZOS-API interface 2024 R1

Example 10 - C#

Last update: 17.07.2025

C#

using System;
using ZOSAPI;
namespace CSharpStandaloneApplication
{
class Program
{
static void Main(string[] args)
{
// Find the installed version of OpticStudio
bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize();
// Note -- uncomment the following line to use a custom initialization path
//bool isInitialized = ZOSAPI_NetHelper.ZOSAPI_Initializer.Initialize(@"C:\Program Files\OpticStudio\");
if (isInitialized)
{
LogInfo("Found OpticStudio at: " + ZOSAPI_NetHelper.ZOSAPI_Initializer.GetZemaxDirectory());
}
else
{
HandleError("Failed to locate OpticStudio!");
return;
}
BeginStandaloneApplication();
}
static void BeginStandaloneApplication()
{
// Create the initial connection class
ZOSAPI_Connection TheConnection = new ZOSAPI_Connection();
// Attempt to create a Standalone connection
IZOSAPI_Application TheApplication = TheConnection.CreateNewApplication();
if (TheApplication == null)
{
HandleError("An unknown connection error occurred!");
return;
}
// Check the connection status
if (!TheApplication.IsValidLicenseForAPI)
{
HandleError("Failed to connect to OpticStudio: " + TheApplication.LicenseStatus);
return;
}
if (TheApplication.Mode != ZOSAPI_Mode.Server)
{
HandleError("User plugin was started in the wrong mode: expected Server, found " + TheApplication.Mode.ToString());
return;
}
IOpticalSystem TheSystem = TheApplication.PrimarySystem;
// Add your custom code here...
// creates new directory
string strPath = System.IO.Path.Combine(TheApplication.SamplesDir, @"API\CS");
System.IO.Directory.CreateDirectory(strPath);
// Open File, Save to New Name
string file = "\\Non-Sequential\\Ray Splitting\\Beam splitter.zos";
TheSystem.LoadFile(TheApplication.SamplesDir + file, false);
TheSystem.SaveAs(TheApplication.SamplesDir + "\\API\\CS\\e10_NSC_ray_trace.zos");
// Run an NSC Ray Trace, Save .zrd file
INSCRayTrace NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace(); // Open NSC RayTrace tool
NSCRayTrace.ClearDetectors(0); // Clear all detectors
// Set up RayTrace tool
NSCRayTrace.IgnoreErrors = true;
NSCRayTrace.SaveRays = true;
NSCRayTrace.SaveRaysFile = "e10_API_RayTrace.ZRD"; // Saves to same directory as lens file
NSCRayTrace.RunAndWaitForCompletion();
NSCRayTrace.Close();
// Open Detector Viewer, view previously saved .zrd file
IA_ DetectorView = TheSystem.Analyses.New_DetectorViewer();
IAS_DetectorViewer DetectorView_Settings = DetectorView.GetSettings() as IAS_DetectorViewer;
DetectorView_Settings.RayDatabaseFilename = "e10_API_RayTrace.ZRD";
DetectorView_Settings.ShowAs = DetectorViewerShowAsTypes.FalseColor;
DetectorView_Settings.Filter = "X_HIT(2, 4)"; // Detector will only display rays which hit object 2 exactly 4 times
DetectorView.ApplyAndWaitForCompletion(); // Apply Settings to Detector Viewer
// Retrieve detector data and detector information
INonSeqEditor TheNCE = TheSystem.NCE;
Double total_hits, total_flux;
Boolean hits_bool_return, flux_bool_return, dims_bool_return;
UInt32 X_detectorDims, Y_detectorDims;
hits_bool_return = TheNCE.GetDetectorData(4, -3, 0, out total_hits); // Object Number=4, Pix -3 & Data=0 (total hits)
flux_bool_return = TheNCE.GetDetectorData(4, 0, 0, out total_flux); // Object Number=4, Pix=0 & Data=0 (total flux)
dims_bool_return = TheNCE.GetDetectorDimensions(4, out X_detectorDims, out Y_detectorDims); // get number of pixels in X, Y
Console.WriteLine("total hits = " + total_hits + "\n" + "total flux = " + total_flux);
UInt32 length = X_detectorDims * Y_detectorDims;
Double[] pix = new Double[length]; // Create array to store flux data for each pixel
Boolean pix_bool;
// mrh: should this be 0 or 1 index, the first Pix# is 1
for (int i = 0; i < length; i++) // loop through pixels, store value in pix
{
pix_bool = TheNCE.GetDetectorData(4, i, 0, out pix[i]);
}
// Save Ray Path Analysis to Text File
if (TheApplication.LicenseStatus == ZOSAPI.LicenseStatusType.PremiumEdition)
{
IA_ RayPath = TheSystem.Analyses.New_Analysis(AnalysisIDM.PathAnalysis);
RayPath_settings.RayDatabaseFile = "e10_API_RayTrace.ZRD";
IAR_ Rays = RayPath.GetResults();
Rays.GetTextFile(TheApplication.SamplesDir + "\\API\\CS\\e10_RayPathAnalysis.txt");
}
else
{
Console.Write("\nThe RayPathAnalysis is a premium feature only\n\nPress any key to continue\n");
Console.ReadKey();
}
// Save!
TheSystem.Save();
Console.WriteLine("Finished! Press any key to leave...");
Console.ReadKey();
// Clean up
FinishStandaloneApplication(TheApplication);
}
static void FinishStandaloneApplication(IZOSAPI_Application TheApplication)
{
// Note - TheApplication will close automatically when this application exits, so this isn't strictly necessary in most cases
if (TheApplication != null)
{
TheApplication.CloseApplication();
}
}
static void LogInfo(string message)
{
// TODO - add custom logging
Console.WriteLine(message);
}
static void HandleError(string errorMessage)
{
// TODO - add custom error handling
throw new Exception(errorMessage);
}
}
}
Definition: ZemaxService.cs:198
IZOSAPI_Application CreateNewApplication()
Attempts to launch a new instance of Optic Studio in 'headless' mode. Note that although the Optic St...
Definition: ZemaxService.cs:863
Properties and methods for retrieving analysis window data. This interface can be accessed via the IA...
Definition: IAR_Base.cs:21
bool GetTextFile(String Filename)
This function provides similar functionality to the DDE and ZPL commands GETTEXTFILE.
Base interface for all analysis windows. This interface can be accessed via the I_Analyses interface.
Definition: IA_Base.cs:29
IAR_ GetResults()
Gets the result data (if available) for the current analysis.
IAS_ GetSettings()
Gets the settings for the current analysis.
IMessage ApplyAndWaitForCompletion()
Re-runs the analysis with the current settings and waits for it to finish calculating.
Definition: IAS_PathAnalysis.cs:40
Definition: IAS_DetectorViewer.cs:23
This interface defines all properties and methods needed to interact with the Non-Sequential Componen...
Definition: InterfacesNCE.cs:363
bool GetDetectorDimensions(int ObjectNumber, out uint Rows, out uint Cols)
Gets the dimensions of the specified detector.
bool GetDetectorData(int ObjectNumber, int pixel, int Data, out double Value)
Gets data from a NSC detector.
Represent a complete optical system. A IOpticalSystem corresponds to a single .ZMX file....
Definition: Interfaces.cs:690
void SaveAs(string fileName)
Saves the current system to the specified file. All future calls to Save will use the same file.
bool LoadFile(string LensFile, bool saveIfNeeded)
Replaces the current system with data from the specified file.
I_Analyses Analyses
Gets the analyses for the current system.
Definition: Interfaces.cs:928
void Save()
Saves the current system.
INonSeqEditor NCE
Gets the non-sequential component editor.
Definition: Interfaces.cs:887
IOpticalSystemTools Tools
Gets an interface used to run various tools on the optical system.
Definition: Interfaces.cs:935
This interface contains all information about the current ZOS-API connection, as well as methods for ...
Definition: Interfaces.cs:264
bool IsValidLicenseForAPI
Gets a value indicating whether this the API is currently useable.
Definition: Interfaces.cs:290
ZOSAPI_Mode Mode
Gets the current connetion mode. Use this to check if Optic Studio is expecting a user operand / anal...
Definition: Interfaces.cs:309
LicenseStatusType LicenseStatus
Gets the license status. Note that this displays the license edition if successful,...
Definition: Interfaces.cs:283
void CloseApplication()
Shut down the Optic Studio process.
IOpticalSystem PrimarySystem
Gets the primary system. When Mode is ZOSAPI_Mode.Server, this will initially be an empty sequential ...
Definition: Interfaces.cs:331
string SamplesDir
Gets the full path for the current user's samples directory (in the My Documents\Zemax\Samples\ folde...
Definition: Interfaces.cs:508
bool RunAndWaitForCompletion()
Sames as calling Run followed by WaitForCompletion.
bool Close()
Closes this tool and frees up and associated resources.
Interfaces and methods for running a non-sequential ray trace. This interface can be accessed via the...
Definition: RayTrace.cs:45
ErrorType ClearDetectors(int DetectorNumber)
Clears the specified detectors.
Definition: IAR_Base.cs:11
Definition: IAS_PathAnalysis.cs:10
Definition: IAS_DetectorViewer.cs:6
Definition: IAS_FieldCurvatureAndDistortion.cs:5
AnalysisIDM
All available analysis types. See the I_Analyses interface for more information.
Definition: I_Analyses.cs:15
DetectorViewerShowAsTypes
Definition: I_ShowAs.cs:34
Definition: InterfacesNCE.cs:19
Definition: RayTrace.cs:12
The ZOSAPI namespace contains classes for initially connecting to zemax. See also ZOSAPI_Connection,...
Definition: IAS_FieldCurvatureAndDistortion.cs:5
ZOSAPI_Mode
Definition: Interfaces.cs:80

Connect with Ansys