Quantcast
Channel: NX Journaling - Journaling / NXOpen API
Viewing all 783 articles
Browse latest View live

Visual Basic: MySQL Database in Journal

$
0
0

Hello

How do I implement a MySQL database in a NX Journal? Do I have to use a compiler like Visual Studio, download the Connector for .Net and create a .dll? Or do I even have to use the licenced editor of Siemens?
By the way, can a .dll compiled with Visual Studio be implemented as a Button in NX?

After that i can just import it with this import, right?Imports MySql.Data.MySqlClient

Thank you and Regards


Body Color

$
0
0

Is there a way to create an expression that is linked to body color without Knowledge Fusion? I have expressions that check for size. When certain sizes, I want the body colors to be corresponding colors. I want it to update the body color when the size changes. I was hoping there would be a journal that could create this expression link to the part attribute for me.

Thanks,

Wayne

Visual Basic: Bounding Box of current part

$
0
0

Hello

I found this Journal which returns the bouding box (dimensions) of a part you can select. I tried to modify it so it doesn't need the selecting anymore, but wasn't successful. How can I do this for the current work part?

It doesn't have to work for assemblys.

Edit: I don't need the directions, just the dimensions of the part as information for shipping. For Example: 150x20x5.

Thank you and Regards

Check if displayed part is assembly

$
0
0

Hello

My Script should only work if it's used in an assembly. What is the best way to check that?
My idea was to try and count the Items in GetChildren(), but it isn't really a clean solution.

Regards

VB: Check current folder directory

$
0
0

Hello

How can I get the current default folder for Teamviewer? (The one it sets default when you try to save a part)
I only know how to set it with
theSession.PdmSession.SetDefaultFolder(":Path")

Also is it possible to check if a folder exists in Teamviewer?

Regards

Auto balloon

$
0
0

I want to generate auto balloon in 2D Drawing . How to start the code ? Please help me . If there is any code which is already available if yes please share with me.

EDM Design Utilities

Read NX Drafting table via NX Open

$
0
0

Hey all, I need to get user input using the Drafting table. Is there any method to get the values written in any cell of the table.I know we can set the value using "EditCellText" method. Is there any method to get the value written in the cell?
If not, what method should be used to get user input in a tabular, visual manner(apart from the expressions window)

Thanks in advance!


Convert "red" dimensions to absolute "blue" ones

$
0
0

Hello

When I create a new extrude my dimensions are red at first. They don't appear in the expressions. Only after I change the values they get blue and absolute.
Picture: 50 is set, 74 is still red and has no name.

This is a problem because I want to get all dimensions of a part. Can I convert all red ones to absolute blue ones? Or is there an other way I can get the Name and value of the red dimensions?

If not, is there at least a way I can check if a part has still some red dimensions in it?

Thank you and Regards

Control NX via Excel VBA using NXOpen commands

$
0
0

Hello everybody,

i'm about to develop a configurator for a NX assembly.
So I have an Excel file with all the data and the userinterface and a NX assembly. My aim is that the user can e.g. click something in the UI and then the NX assembly changes according to the users input.
I want to do these changes of the assmbly with NX Open commands (replace components, update values, export BOM Files, clone assemblies, create drawings etc.).
This code should be stored inside of the Excel VBA. So the user can invoke the code with action buttons in the userinterface.
Do you know if this is possible?
I tried to find a reference of NX for Excel VBA but i was not able to find something suitable.
Does anyone have the same problem?

Thanks in advance!

Kind regards,
Lorenz Weber

Mass assigned to all the bodies

$
0
0

Hi ladies and gentlemen,

I'm new to Jorunal Programming. I'm looking for a solution to a problem.
In NX 12 at the component level, there must be a mass assigned to all the bodies within the component. (All Volume body!)
In the message box, you should enter the weight of the component and calculate the density in proportion to the total volume. The total weight of the component should be the same as the value entered.

I can use VB and Pyton too.

Thanks a lot.

Random appearance color to selected components?

$
0
0

Hello,

Thanks for taking the time to look at this. I know very little about this subject but am fumbling my way through it. What I would like is a journal that applies a random color to each of the selected components. I know there is an appearance setting for this but that does not give me the results I desire. I have searched and found code originally posted here by NXJournaling that is very close. I have modified it to produce a random color, however it applies this same random color to each component. I would like each component that is selected to have a different random color. I know it needs to be in some sort of loop but I have no idea how to make that happen. Anyway, below is the code:

Option Strict Off
Imports System
Imports System.Collections.Generic
Imports NXOpen
Imports NXOpenUI
 
 
Module Module1
 
    Sub Main()
 
        Dim theSession As Session = Session.GetSession()
        Dim theUI As UI = UI.GetUI
 
        If IsNothing(theSession.Parts.BaseWork) Then
            'active part required
            Return
        End If
 
        Dim numsel As Integer = theUI.SelectionManager.GetNumSelectedObjects()
        Dim theComps As New List(Of Assemblies.Component)
 
 
 
        For i As Integer = 0 To numsel - 1
            Dim selObj As TaggedObject = theUI.SelectionManager.GetSelectedTaggedObject(i)
            If TypeOf (selObj) Is Assemblies.Component Then
                theComps.Add(selObj)
 
            End If
 
        Next
 
        If theComps.Count = 0 Then
            'no components found among the preselected objects
            Return
        End If
 
 
 
 
	randomize
	Dim mycolor as integer = Int ((216-1) * Rnd + 1)
 
 
 
        Dim markId1 As Session.UndoMarkId
        markId1 = theSession.SetUndoMark(Session.MarkVisibility.Visible, "Edit Object Display")
 
        Dim displayModification1 As DisplayModification
        displayModification1 = theSession.DisplayManager.NewDisplayModification()
 
        With displayModification1
            .ApplyToAllFaces = False
            .ApplyToOwningParts = False
 
 
            .NewColor = mycolor
            .Apply(theComps.ToArray)
 
        End With
        displayModification1.Dispose()
 
 
 
    End Sub
 
 
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
 
        'Unloads the image immediately after execution within NX
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately
 
    End Function
 
End Module

FilePath with special characters

$
0
0

Hi all,

I am trying to export step models by a script written in python. I experienced problems with that, when the path to the part file contains special characters such as German ä, ö, ü and maybe other.

Let's say the path to the part for is
C:\ORDNÄR\my part.prt

The property workpart.FullPath returns
C:\ORDNR\my part.prt

Does anyone know a solution for this?

How to edit existing expression?

$
0
0

Hello

Below is a journal that creates an expression and if run the second time it should edit expression value that was created in the first run. Do i need another block of code to handle errors?

Imports System
Imports NXOpen
 
Module create expression
 
    Public theSession As Session = Session.GetSession()Public workPart As Part = theSession.Parts.Work 
    Sub Main() 
        Dim leftPart AsString="12"Dim expression1 As NXOpen.Expression=NothingDim thr_exp As NXOpen.Expression=NothingDim expression_a AsString="thr_txt" 
        'create expression 
        TryDim theExp As Expression = workPart.Expressions.FindObject(expression_a) 
            workPart.Expressions.Edit(theExp, "M""+stringValue( "& leftPart &" )") 
        Catch ex As NXException
            ex.AssertErrorCode(3520016) 
            expression1 = workPart.Expressions.CreateExpression("String", expression_a &"=""M""+stringValue( "& leftPart &" )")EndTry 
    EndSub 
    PrivateSub Echo(ByVal output AsString)
        theSession.ListingWindow.Open()
        theSession.ListingWindow.WriteLine(output)
        theSession.LogFile.WriteLine(output)EndSub 
    PublicFunction GetUnloadOption(ByVal arg AsString)AsIntegerReturn System.Convert.ToInt32(Session.LibraryUnloadOption.Immediately)EndFunction 
EndModule

export Parts listTable Information in Drafting to Excel file

$
0
0

hello,
I want to export the information in the parts list to an excel file. My idea is to use the Select Object function to select a table and then export the information in the table to an excel file. Can someone point me to this?


workview.askvisibleobjecs

$
0
0

Hi,

I am clipping the work view to a particular component using clip section - type- Box.
Now after clipping only the particular components inside the box is visible..
But when i askvisible objects of this, it is returning all the objects..my objective is to get only the components inside the clip section box. I tried interactively , by giving cntrl+A and also selecting all using select all in object selection. It is selecting only the objects in the clip section. i need to replicate this behaviour. When i recorded, select all it is asking to see GTAC sample code for select all.. But again all those codes use workview.ask visible objects..so it is not useful. Could some one suggest anyother way to get all the objects inside a clip section box

Mirrored/Linked bodies not exporting

$
0
0

I've written a script to loop over all the bodies in an assembly and identify ones that match a certain NX_material string. These are then exported as STLs later.

However, parts that appear to be links/mirrors (I don't know the right NX terminology) are not exported, only the root part is exported.

As I loop over the bodies, though, and set the setHighlight flag to "1", all the mirrored/linked parts are highlighted, for a given body, but later, the ExportSTL call only exports one of these.

How can I export all occurrences (?) of this part.

Here's the full VB script with a few sensitive pieces of information removed:

Option Strict Off
Imports System
Imports System.ThreadingImports System.Collections.GenericImports NXOpen
Imports NXOpen.UFImports NXOpen.AssembliesImports NXOpen.Features 
Module Module1
 
    Dim theSession As Session = Session.GetSession()Dim theUfSession As UFSession = UFSession.GetUFSession()Dim lw As ListingWindow = theSession.ListingWindow 
	Dim bCheckIfFullyLoaded AsBoolean=FalseDim stlOutFileName AsString="C:/This/is/a/path"Dim qualifiers AsString=""Dim materialList AsNew List(OfString)From{"Material_name_1", "Material_name_2"} 
 
	Dim bWriteSTL AsBoolean=FalseDim bWriteAsIndividualFiles AsBoolean=False 
    Sub Main() 
        If IsNothing(theSession.Parts.BaseWork)Then'active part requiredReturnEndIf 
        Dim workParts AsNew List(Of Part)ForEach tempPart As Part In theSession.Parts'Dim c As ComponentAssembly = tempPart.ComponentAssembly
			workParts.Add(tempPart)Next 
        lw.Open() 
        Const undoMarkName AsString="export solids to STL"Dim markId1 As Session.UndoMarkId
        markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, undoMarkName) 
        Dim theSolids AsNew List(Of Body) 
        'collect the solid bodies in the work part 
		ForEach part As Part in workParts
			Dim isLoadead AsBoolean= part.IsFullyLoaded()Dim partDesc AsString= part.GetStringAttribute("DB_PART_DESC")
			lw.WriteLine(part.Name+" "+ partDesc) 
			If bCheckIfFullyLoaded ThenIf isLoadead Then
					lw.WriteLine(" Fully Loaded")Else
					lw.WriteLine(" Not Fully Loaded")
					lw.WriteLine("  Trying to fully load this part")Try
						part.LoadThisPartFully()Catch ex As Exception
						lw.WriteLine("Error: "+ ex.Message)EndTryEndIfEndIf 
			ForEach body As Body In part.Bodies
				lw.WriteLine("-"+ body.Name)
				theUfSession.Disp.SetHighlight(body.Tag, 0)If body.HasUserAttribute("NX_Material", NXObject.AttributeType.String, 0)ThenDim obj As NXOpen.NXObject.AttributeInformation= body.GetUserAttribute("NX_Material", NXObject.AttributeType.String, -1)Dim material AsString= obj.StringValue 
					lw.WriteLine("... "+ material) 
					Dim bKeepThisBody AsBoolean=FalseDim bContinue =False 
					ForEach mat AsStringIn materialList
						If material.Contains(mat)Then
							bContinue =TrueEndIf 
						' HACK to get a portion of the rollbar selectedIf mat ="SPECIAL_NAME"ThenIf partDesc.Contains("ROLLBAR")And material.Contains("ZERO MASS")Then
								bContinue =TrueEndIfEndIfNext 
 
					If bContinue ThenIf qualifiers <>""ThenForEach feature As Feature in body.GetFeatures()If feature.Name.Contains(qualifiers)
									bKeepThisBody =TrueEndIfNextElse
							bKeepThisBody =TrueEndIf 
						If bKeepThisBody Then
							theUfSession.Disp.SetHighlight(body.Tag, 1)
							theUfSession.Disp.MakeDisplayUpToDate()
							System.Threading.Thread.Sleep(200) 
							theUfSession.Disp.SetHighlight(body.Tag, 0)
							theUfSession.Disp.MakeDisplayUpToDate()
							lw.WriteLine(body.Name)
							theSolids.Add(body)EndIfEndIfEndIfNextNext 
 
		If bWriteSTL ThenIf bWriteAsIndividualFiles
				ForEach body As Body In theSolids
					Dim singleObject AsNew List(Of Body)
					singleObject.Add(body)
					ExportSTL(stlOutFileName +"_"+CStr(body.Tag), singleObject, 0.03)NextElse
				ExportSTL(stlOutFileName, theSolids, 0.03)EndIfEndIf'Try'ExportSTL(workPart.FullPath, theSolids, 0.003, 0.003)'Catch ex As NXException'lw.WriteLine("NX Error: " & ex.Message)'Catch ex As Exception'lw.WriteLine("Error: " & ex.Message)'End Try 
        lw.Close() 
    EndSub 
 
    Sub ExportSTL(ByVal FileName AsString, ByVal theObjects As List(Of Body), ByVal triangleTolerance AsDouble) 
        Dim NumErrors AsIntegerDim FileHandle As IntPtr
        Dim InfoError()As UFStd.StlErrorDim Header, FileBaseName AsStringDim lw As ListingWindow = theSession.ListingWindowDim theUfSession As UFSession = UFSession.GetUFSession()'Dim numNegated As Integer'Dim Negated() As Tag 
		lw.Open()'Negated = Nothing
        InfoError =Nothing 
        FileName = IO.Path.ChangeExtension(FileName, ".stl") 
        FileBaseName = IO.Path.GetFileName(FileName)
        Header ="Header: "& FileBaseName
 
        theUfSession.Std.OpenBinaryStlFile(FileName, False, Header, FileHandle) 
        theUfSession.Ui.SetPrompt("Creating file ... "& FileBaseName &" ...") 
        ForEach temp As Body In theObjects
            If temp.IsSolidBodyThen
				lw.WriteLine(" body is occurrence: "+ temp.IsOccurrence.ToString)Try
					theUfSession.Std.PutSolidInStlFile(FileHandle, Tag.Null, temp.Tag, 0.0, 5.0, triangleTolerance, NumErrors, InfoError)
					theUfSession.Disp.SetHighlight(temp.Tag, 0)Catch ex As Exception
					lw.WriteLine("Error with STL : "+ ex.Message)EndTryEndIfNext 
        theUfSession.Std.CloseStlFile(FileHandle) 
        theUfSession.Ui.SetStatus("File ... "& FileBaseName &" generated ...") 
    EndSub 
    PublicFunction GetUnloadOption(ByVal dummy AsString)AsInteger 
        'Unloads the image immediately after execution within NX
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately 
    EndFunction 
EndModule

Export STL foreach component in assembly

$
0
0

Hi everyone,
I'm searching for a solution to export STL files from my assembly.

I try to be clear with my question:

We suppose to have an assembly so made:

Assembly (level 0)
- Subassembly_1 (Level 1)
-Component_1 (Level 2)
-Component_2 (Level 2)
- Subassembly_2 (Level 1)
-Component_3 (Level 2)
-Component_4 (Level 2)
-Subassembly_3 (Level 2)
-Component 5 (Level 3)
-Component 6 (Level 3)

and so on....

If assembly is set as current workpart, I can't see bodies contained in all subcomponents.
Currently, I go through the hierarchy by setting each time the current component as workpart. In this way, I export all bodies as one stl files by means of the method that I found in the other topic. The entire procedure is too time-consuming in the case of thousands of parts.
My question is the following:

Is there a method to get bodies of a component without setting it as the current workpart?

Thank you very much!

Exporting Parts with NX Journal

$
0
0

I would like to Export all the parts of my assembly.

To do this I have done File -> Export ->Parts
My specifications for the Export Part menu are the following:
Part Specification: New
Specify Part: "newprt.prt"
Object Selection Scope: All Objects
Class Selections: Select All
Highlight Choice: Selected Objects
Feature Parameters: Remove Parameters
Expression Transfer Mode: Copy if Referenced.

This works for what I am trying to do. However, after recording a journal of Exporting the parts, when I attempt to run the journal again, the program does not save the new file name ("newprt.prt) and therefore can not open the file which is being exported. How would I get the journal to record my Specify Part filename? Any advice?

Here is the portion of the journal where I attempt to export the part and open the exported file:

' NX 1863
 
Imports System
Imports NXOpen
 
Module NXJournal
Sub Main (ByVal args() As String) 
 
Dim theSession As NXOpen.Session = NXOpen.Session.GetSession()
' ----------------------------------------------
'   Menu: File->Open...
' ----------------------------------------------
Dim basePart1 As NXOpen.BasePart = Nothing
Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
basePart1 = theSession.Parts.OpenActiveDisplay("H:newprt.SLDPRT", NXOpen.DisplayPartOption.AllowAdditional, partLoadStatus1)
 
Dim workPart As NXOpen.Part = theSession.Parts.Work
 
Dim displayPart As NXOpen.Part = theSession.Parts.Display
 
partLoadStatus1.Dispose()
theSession.ApplicationSwitchImmediate("UG_APP_GATEWAY")
 
' ----------------------------------------------
'   Menu: File->Export->Part...
' ----------------------------------------------
' ----------------------------------------------
'   Dialog Begin Export Part
' ----------------------------------------------
Dim markId1 As NXOpen.Session.UndoMarkId = Nothing
markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start")
 
theSession.SetUndoMarkName(markId1, "Class Selection Dialog")
 
' ----------------------------------------------
'   Dialog Begin Class Selection
' ----------------------------------------------
' Refer to the sample NXOpen application, Selection for "Select All" alternatives.
Dim markId2 As NXOpen.Session.UndoMarkId = Nothing
markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Class Selection")
 
theSession.DeleteUndoMark(markId2, Nothing)
 
Dim markId3 As NXOpen.Session.UndoMarkId = Nothing
markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Class Selection")
 
theSession.DeleteUndoMark(markId3, Nothing)
 
theSession.SetUndoMarkName(markId1, "Class Selection")
 
theSession.DeleteUndoMark(markId1, Nothing)
 
' ----------------------------------------------
'   Dialog Begin Export Part
' ----------------------------------------------
' ----------------------------------------------
'   Menu: File->Open...
' ----------------------------------------------
Dim basePart2 As NXOpen.BasePart = Nothing
Dim partLoadStatus2 As NXOpen.PartLoadStatus = Nothing
basePart2 = theSession.Parts.OpenActiveDisplay("H:newprt.prt", NXOpen.DisplayPartOption.AllowAdditional, partLoadStatus2)
<code>

Updating vintage part files

$
0
0

Hi there,
I have made up a nice journal which should help making a "face lift" to vintage UG and NX files as far as appearance is affected: Background colors, body colors, color palette, vizualization preferences - especially selection and pre-selection color.
My aim is to have this run against all parts that are currently opened in an NX session so it cycles all parts in the session. But this has 2 donwsides:
1. I cannot make use of MACRO_playback (see the commented call @ line 115) to just set the color palette to system standard (a function which is not supported by the jounal recorder, so I used macro instead) so I used a code to open the .CDF file and set all colors accordingly,
2. For whatever reason, when it comes to setting the vizualization standards, especially selection colors, my journal has only effect on the single part which was the display part when I start running the journal.
I have tried to make NX switch the display part while cycling through the parts but maybe there's something wrong at that point (@ line 49ff).

Here's my code:

' Dieses Programm...
' - stellt die Hintergrundfarbe für schattierte Darstellung ein auf den NX1899 Standard
' - orientiert das Modell auf "TRIMETRIC", passt es ein und 
'   richtet die Anzeigefacetten neu aus (wirksam ab NX1899)
' - Startet ein externes Makro, das die System-Farbpalette lädt
'   Den Pfad für das externe Makro unbedingt an die Implementierungsumgebung anpassen!
' - Prüft alle Flächen aller Körper im Part auf zulässige Farbe 
'   und ändert unzulässige Farben auf 129
' - und noch mehr (tbd!)
'  03.04.2020
 
' Anwendung: Partfiles in NX Modeling laden
' [Alt]+[F8] -> Zur Journaldatei browsen, dann Journal ausführen
 
 
Imports System
Imports System.IO
Imports System.Windows.Forms
Imports System.Globalization
 
Imports NXOpen
Imports NXOpen.UF               '.Net wrapped User Function
 
Module NXJournal
 
Declare Sub MACRO_playback_from_usertool Lib "libugui" Alias "?MACRO_playback_from_usertool@@YAXPEBD@Z" (ByVal lpName As String)
 
Dim theSession As Session = Session.GetSession()
Dim theUFSession As UFSession = UFSession.GetUFSession()
 
 
Sub Main (ByVal args() As String) 
	Dim markId42 As NXOpen.Session.UndoMarkId = Nothing
	markId42 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start")	
	theSession.SetUndoMarkName(markId42, "Display Adjustment")
 
	Dim workPart As NXOpen.Part = theSession.Parts.Work
	Dim displayPart As NXOpen.Part = theSession.Parts.Display
 
	Dim allParts() As BasePart = theSession.Parts.ToArray
 
	Dim nXObject1 As NXOpen.NXObject = Nothing
 
	' Iterate through the parts in the session
	For Each thisBasePart As BasePart In allParts
		Dim thisPart As Part = CType(thisBasePart, Part)
		Echo("Adjusting: " & thisPart.FullPath())
 
        ' Change the Displayed part
        Dim partLoadStat As PartLoadStatus
        'Dim displayPart As Part
        theSession.Parts.SetDisplay(thisBasePart, False, False, partLoadStat)
        'displayPart = thisBasePart		
 
 
		' Hintergrundfarbe angleichen
		Dim background1 As NXOpen.Display.Background = Nothing
		background1 = displayPart.Views.CreateBackground(displayPart.ModelingViews.WorkView, False)
		Dim topcolor1(2) As Double
		topcolor1(0) = 0.70588000000000000  '180
		topcolor1(1) = 0.71373000000000000  '182
		topcolor1(2) = 0.72157000000000000  '184
		background1.SetBackgroundShadedViewsGraduatedTop(topcolor1)
 
		'Dim nXObject1 As NXOpen.NXObject = Nothing
 
		Dim bottomcolor1(2) As Double
		bottomcolor1(0) = 0.90196000000000000  '230
		bottomcolor1(1) = 0.90980000000000000  '232
		bottomcolor1(2) = 0.91765000000000000  '234
		background1.SetBackgroundShadedViewsGraduatedBottom(bottomcolor1)
 
		Dim nXObject2 As NXOpen.NXObject = Nothing
		nXObject2 = background1.Commit()
 
		' Teil auf "TRIMETRIC" orientieren, einpassen und Anzeigefacetten neu ausrichten (ab NX1899)
		displayPart.ModelingViews.WorkView.Orient(NXOpen.View.Canned.Trimetric, NXOpen.View.ScaleAdjustment.Fit)
		displayPart.ModelingViews.WorkView.UpdateDisplay()
 
 
 
		'Körperfarben neu setzen
		Dim okColor As Boolean = False
		Dim acceptableColors() As Integer = {129, 171} 'Solid, Face
 
		' Iterate through the bodies in the part
		Dim allBodies() As Body = thisPart.Bodies.ToArray
 
		For Each thisBody As Body In allBodies
			' Iterate through all of the faces on that body
			Dim allFaces() As Face = thisBody.GetFaces()
			For Each thisFace As Face In allFaces
				' Start out by assuming that the color of this face is bad
				okColor = False
				' Check it against all of the approved colors.
				For inx As Integer = 0 To acceptableColors.GetUpperBound(0)
					If thisFace.Color = acceptableColors(inx) Then
						' As soon as we find that it matches a good color, we jump
						' out of that loop and move to the next face.
						okColor = True
						Continue For
					Else
						'Echo("Changing the Colour...")
						thisFace.Color = 129
						thisFace.RedisplayObject()
					End If
				Next inx
				If okColor = False Then
					'Echo("    Bad color found in this part.")
				End If
			Next thisFace
		Next thisBody
 
		' System-Farbpalette laden via Macro	
		'MACRO_playback_from_usertool("C:\Daten_UM\05 - in Arbeit\Marcel Schmid\LoadSystemColorPalette.macro")
 
		' Farbpalette aus .CDF laden
        Dim colorName As String = ""
        Dim red As String = ""
        Dim green As String = ""
        Dim blue As String = ""
        Dim rgbColor(2) As Double
 
        Dim provider  As NumberFormatInfo = new NumberFormatInfo( )
        provider.NumberDecimalSeparator = "."
        provider.NumberGroupSeparator = ","
        provider.NumberGroupSizes = New Integer( ) { 3 }
        provider.NumberDecimalDigits = 6
 
        Dim thisColor As Integer = 0		
        Dim textLine As String = ""
        Dim lineCounter As Integer = 0
        'Dim myStream As Stream = Nothing
        Dim UGIIBaseDir As String = Environment.GetEnvironmentVariable("UGII_BASE_DIR")
		Dim Filename As String = "C:\PLM\NX1899\UGII\ugcolor.cdf"
		Dim myStream As New System.IO.StreamReader( Filename )
		'Dim openFileDialog1 As New OpenFileDialog()
 
        Dim rootDir As String = _
            Environment.GetEnvironmentVariable("UGII_BASE_DIR")&"\ugii"
 
        Try
            Dim charsToTrim() As Char = {" "c}
 
            If (myStream IsNot Nothing) Then
                'Dim fileReader As New StreamReader(myStream)
                Do
                    textLine = myStream.ReadLine()
 
                    If lineCounter > 3 Then
 
                        colorName = textLine.Substring(0, 30)
                        colorName = colorName.TrimEnd(charsToTrim) ' Remove trailing spaces
 
                        red = textLine.Substring(34, 8)
                        green = textLine.Substring(45, 8)
                        blue = textLine.Substring(56, 8)
 
                        rgbColor(0) = Convert.ToDouble(red,provider)
                        rgbColor(1) = Convert.ToDouble(green,provider)
                        rgbColor(2) = Convert.ToDouble(blue,provider)
                        thisColor = lineCounter - 4
 
                       '   Echo("Color Name=" + colorName + " -- " + _
                       '"This Color=" + thisColor.ToString() + _
                       '" R=" + rgbColor(0).ToString() + _
                       '" G=" + rgbColor(1).ToString() + _
                       '" B=" + rgbColor(2).ToString())
					   '
                        theUFSession.Disp.SetColor(thisColor, UFConstants.UF_DISP_rgb_model, colorName, rgbColor)
                    End If
                    lineCounter += 1
                Loop Until myStream.EndOfStream().Equals(True)
 
                theUFSession.Disp.LoadColorTable()
            End If
        Catch Ex As NXException
            MessageBox.Show("Error: " & Ex.Message)
        Finally
            If (myStream IsNot Nothing) Then
                myStream.Close()
                theUFSession.Ui.SetStatus("Loaded CDF")
            End If
        End Try
 
		' Visualisierungseinstellungen auf Standard setzen
 
		Dim pixelwidths1(8) As Integer
		pixelwidths1(0) = 1
		pixelwidths1(1) = 1
		pixelwidths1(2) = 1
		pixelwidths1(3) = 1
		pixelwidths1(4) = 2
		pixelwidths1(5) = 2
		pixelwidths1(6) = 3
		pixelwidths1(7) = 3
		pixelwidths1(8) = 3
		displayPart.Preferences.LineVisualization.SetPixelWidths(pixelwidths1)
 
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.ShadedEdgeStyle = NXOpen.Preferences.ViewVisualizationVisual.ShadedEdgeStyleType.ShadedEdgeColor
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.ShadedEdgeColor = 173
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.HiddenEdgeStyle = NXOpen.Preferences.ViewVisualizationVisual.HiddenEdgeStyleType.Invisible
		displayPart.Preferences.ColorSettingVisualization.HiddenGeometryColor = 44
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.TwoSidedLight = True
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.ShininessData = 0.34999999999999998
 
		Dim displayAppearanceOptions1 As NXOpen.Preferences.ViewVisualizationVisual.DisplayAppearanceOptions = Nothing
		displayAppearanceOptions1.RenderingStyle = NXOpen.Preferences.ViewVisualizationVisual.RenderingStyle.Shaded
		displayAppearanceOptions1.HiddenEdges = NXOpen.Preferences.ViewVisualizationVisual.HiddenEdges.Invisible
		displayAppearanceOptions1.Silhouettes = True
		displayAppearanceOptions1.SmoothEdges = True
		displayAppearanceOptions1.SmoothEdgeColor = 0
		displayAppearanceOptions1.SmoothEdgeFont = NXOpen.Preferences.ViewVisualizationVisual.SmoothEdgeFont.Original
		displayAppearanceOptions1.SmoothEdgeWidth = NXOpen.Preferences.ViewVisualizationVisual.SmoothEdgeWidth.Original
		displayAppearanceOptions1.SmoothEdgeAngleTolerance = 0.19999999999999996
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.DisplayAppearance = displayAppearanceOptions1
 
		Dim displayAppearanceOptions2 As NXOpen.Preferences.ViewVisualizationVisual.DisplayAppearanceOptions = Nothing
		displayAppearanceOptions2.RenderingStyle = NXOpen.Preferences.ViewVisualizationVisual.RenderingStyle.Shaded
		displayAppearanceOptions2.HiddenEdges = NXOpen.Preferences.ViewVisualizationVisual.HiddenEdges.Invisible
		displayAppearanceOptions2.Silhouettes = True
		displayAppearanceOptions2.SmoothEdges = True
		displayAppearanceOptions2.SmoothEdgeColor = 0
		displayAppearanceOptions2.SmoothEdgeFont = NXOpen.Preferences.ViewVisualizationVisual.SmoothEdgeFont.Original
		displayAppearanceOptions2.SmoothEdgeWidth = NXOpen.Preferences.ViewVisualizationVisual.SmoothEdgeWidth.Original
		displayAppearanceOptions2.SmoothEdgeAngleTolerance = 0.20000000000000001
		displayPart.ModelingViews.WorkView.VisualizationVisualPreferences.DisplayAppearance = displayAppearanceOptions2
		displayPart.Preferences.ShadeVisualization.ShadedViewTolerance = NXOpen.Preferences.PartVisualizationShade.ShadedViewToleranceType.Standard
		displayPart.Preferences.ShadeVisualization.ShadedViewUpdateMode = NXOpen.Preferences.PartVisualizationShade.ViewUpdateModeType.VisibleBodiesAndCurves
 
		Dim facetSettingsBuilder1 As NXOpen.Display.FacetSettingsBuilder = Nothing
		facetSettingsBuilder1 = displayPart.CreateFacetSettingsBuilder()
		facetSettingsBuilder1.ShadedAlignFacets = False
 
		displayPart.Preferences.ShadeVisualization.AdvancedVisViewUpdateMode = NXOpen.Preferences.PartVisualizationShade.ViewUpdateModeType.VisibleBodiesAndCurves
 
		facetSettingsBuilder1.AdvVisAlignFacets = True
		facetSettingsBuilder1.AdvVisUpdate = 3
		facetSettingsBuilder1.ShadedUpdate = 3
		nXObject1 = facetSettingsBuilder1.Commit()
		facetSettingsBuilder1.Destroy()
 
		displayPart.Preferences.PerformanceVisualization.SaveAdvancedDisplayFacets = True
		displayPart.Preferences.NamesBorderVisualization.ShowModelViewNames = False
 
		Dim shelloptions1 As NXOpen.Preferences.PartVisualizationEmphasis.ShellOptions = Nothing
		shelloptions1.Rgb.R = 0.69411764705882351
		shelloptions1.Rgb.G = 0.69411764705882351
		shelloptions1.Rgb.B = 0.69411764705882351
		shelloptions1.Edges = NXOpen.Preferences.PartVisualizationEmphasis.EdgesType.Normal
		shelloptions1.EdgesRgb.R = 0.59999999999999998
		shelloptions1.EdgesRgb.G = 0.59999999999999998
		shelloptions1.EdgesRgb.B = 0.59999999999999998
		shelloptions1.Translucency = 75
		displayPart.Preferences.EmphasisVisualization.SetShellOptions(shelloptions1)
 
		Dim originalcolorshelloptions1 As NXOpen.Preferences.PartVisualizationEmphasis.OriginalColorShellOptions = Nothing
		originalcolorshelloptions1.Edges = NXOpen.Preferences.PartVisualizationEmphasis.EdgesType.Normal
		originalcolorshelloptions1.EdgesRgb.R = 0.59999999999999998
		originalcolorshelloptions1.EdgesRgb.G = 0.59999999999999998
		originalcolorshelloptions1.EdgesRgb.B = 0.59999999999999998
		originalcolorshelloptions1.Translucency = 75
		displayPart.Preferences.EmphasisVisualization.SetOriginalColorShellOptions(originalcolorshelloptions1)
 
		Dim layersoptions1 As NXOpen.Preferences.PartVisualizationEmphasis.LayersOptions = Nothing
		layersoptions1.Rgb.R = 0.80000000000000004
		layersoptions1.Rgb.G = 0.80000000000000004
		layersoptions1.Rgb.B = 0.80000000000000004
		layersoptions1.Edges = NXOpen.Preferences.PartVisualizationEmphasis.EdgesType.Normal
		layersoptions1.EdgesRgb.R = 0.59999999999999998
		layersoptions1.EdgesRgb.G = 0.59999999999999998
		layersoptions1.EdgesRgb.B = 0.59999999999999998
		layersoptions1.Translucency = 85
		displayPart.Preferences.EmphasisVisualization.SetLayersOptions(layersoptions1)
		displayPart.Preferences.LineVisualization.ShowWidths = True
		displayPart.Preferences.LineVisualization.ShowWidths = True
		Dim pixelwidths2(8) As Integer
		pixelwidths2(0) = 1
		pixelwidths2(1) = 1
		pixelwidths2(2) = 1
		pixelwidths2(3) = 1
		pixelwidths2(4) = 2
		pixelwidths2(5) = 2
		pixelwidths2(6) = 3
		pixelwidths2(7) = 3
		pixelwidths2(8) = 3
		' UI Colors (Selection etc.)
		displayPart.Preferences.LineVisualization.SetPixelWidths(pixelwidths2)
		displayPart.Preferences.ColorSettingVisualization.PreselectionColor = 149
		displayPart.Preferences.ColorSettingVisualization.SelectionColor = 76
		displayPart.Preferences.ColorSettingVisualization.HiddenGeometryColor = 44
		displayPart.Preferences.ColorSettingVisualization.MonochromePreselectionColor = 149
		displayPart.Preferences.ColorSettingVisualization.MonochromeSelectionColor = 76
		displayPart.Preferences.ColorSettingVisualization.MonochromeBackgroundColor = 1
		theSession.CleanUpFacetedFacesAndEdges()
 
	Next thisBasePart
 
End Sub
 
    Sub Echo(ByVal output As String)
 
        theSession.ListingWindow.Open()
        theSession.ListingWindow.WriteLine(output)
        theSession.LogFile.WriteLine(output)
 
    End Sub
 
End Module

If you want to run it, dont' forget to change the filename in line 135 to an appropriate value. I have tested on NX1907 but most of it should also work in older NX versions.
I'd like to figure out how to set the color palette to system standard using vb and how to have all the parts visualization preferences set correclty, not just the 1st part's.
Any help is much appreciated.
Cheers,
Udo

Viewing all 783 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>