NXOpen 对选择的组件重命名

代是根据NX处身的例子AssemblyViewer代码改装和抄了卢大师部份代码,有些多余的代码和控件没有整理(仅用代码把多余的控件控制不显示面已)。测试过功能是正常的。

 

可在装配树选择部件改名,也可以直接选择部件改名。


======================================================================================

HPP

======================================================================================
#include <uf_defs.h>
#include <uf_ui_types.h>
#include <iostream>
#include <NXOpen/Session.hxx>
#include <NXOpen/UI.hxx>
#include <NXOpen/NXMessageBox.hxx>
#include <NXOpen/Callback.hxx>
#include <NXOpen/NXException.hxx>
#include <NXOpen/BlockStyler_UIBlock.hxx>
#include <NXOpen/BlockStyler_BlockDialog.hxx>
#include <NXOpen/BlockStyler_PropertyList.hxx>
#include <NXOpen/BlockStyler_Tree.hxx>
#include <NXOpen/BlockStyler_Node.hxx>
#include <NXOpen/BlockStyler_Group.hxx>
#include <NXOpen/BlockStyler_Enumeration.hxx>
#include <NXOpen/BlockStyler_SelectObject.hxx>
#include <NXOpen/BlockStyler_ObjectColorPicker.hxx>
#include <NXOpen/BlockStyler_Button.hxx>
#include <NXOpen/BlockStyler_StringBlock.hxx>
#include <NXOpen/BlockStyler_Toggle.hxx>
#include <NXOpen/ListingWindow.hxx> //打印信息
#include <NXOpen/NXException.hxx> //异常处理


//用户头文件
#include <NXOpen/Part.hxx>
#include <NXOpen/BasePart.hxx>
#include <NXOpen/PartCollection.hxx>
#include <NXOpen/Assemblies_Component.hxx>
#include <NXOpen/Assemblies_ComponentAssembly.hxx>
#include <NXOpen/DisplayManager.hxx>
#include <NXOpen/DisplayModification.hxx>
#include <NXOpen/DisplayableObject.hxx>
#include <NXOpen/PartCleanup.hxx>
#include <NXOpen/NXObjectManager.hxx>
#include <uf.h>
#include <uf_ui.h>
#include <string.h>
#include <uf_modl.h>
#include <uf_part.h>
#include <uf_curve.h>
#include <uf_assem.h>
#include <uf_obj.h>
#include <windows.h>
#include <stdarg.h>
#include <strstream>
#include <sstream>
#include <io.h>
#undef CreateDialog


//用户代码
using std::string;
using std::exception;
using std::stringstream;
using std::endl;
using std::cout;
using std::cerr;


//用户代码
void PopulateTree(NXOpen::Assemblies::Component *);// 循环遍历组装组件并填充树列表
void HighlightComponent(std::vector<NXOpen::TaggedObject *>&selObjectData, bool highlight);// 突出显示所选的组件
void ComponentSelection();// 根据IsSingleComponentSelection,选择是针对单个组件还是针对所有组件
std::vector<NXOpen::TaggedObject *> GetComponentOccurences(std::vector<NXOpen::Assemblies::Component *>&assemblyComponent);//获取组件的出现次数
std::vector<NXOpen::TaggedObject *> GetSelectedNodes();// 从树列表中获取所选节点的标记
std::vector<NXOpen::TaggedObject *> GetSelectedObjects();// 从选择对象块中获取所选对象的标记
bool IsSingleComponentSelection();// 指定组件选择选项是“单个组件”还是“所有组件”
void PartCleanup();// 执行部分清理并关闭高亮显示
bool drawAll;// 这个变量决定是选择单个组件,还是基于组件选择选项选择出现的所有组件
std::vector<NXOpen::BlockStyler::Node *> treeNodes;
void setUI();//设置


void focusNotify_cb(NXOpen::BlockStyler::UIBlock* block, bool focus);
void keyboardFocusNotify_cb(NXOpen::BlockStyler::UIBlock* block, bool focus);
void OnSelectCallback(NXOpen::BlockStyler::Tree *tree, NXOpen::BlockStyler::Node *, int columnID, bool selected);

//用户代码
int DelectValue;//对话框返回值,决定是否删除原组件
string NameOrPath(const char* Path, int Type);//返回.prt文件名字和所在文件夹路径
string strDir;
void filesearch(string path, int layer);//遍历文件夹所有.prt文件
char part_name[MAX_FSPEC_SIZE+1];//当前显示部件.prt文件所在路径
char OriginalName[133];//字符串输入对话框值


======================================================================================

CPP

======================================================================================

//------------------------------------------------------------------------------
//These includes are needed for the following template code
//------------------------------------------------------------------------------
#include "RenameComponent.hpp"
using namespace NXOpen;
using namespace NXOpen::BlockStyler;
using namespace NXOpen::Assemblies;

//------------------------------------------------------------------------------
// Initialize static variables
//------------------------------------------------------------------------------
Session *(RenameComponent::theSession) = NULL;
UI *(RenameComponent::theUI) = NULL;

//------------------------------------------------------------------------------
// Declaration of global variables
//------------------------------------------------------------------------------
RenameComponent *theAssemblyViewer;


//------------------------------------------------------------------------------
// Constructor for NX Styler class
//------------------------------------------------------------------------------
RenameComponent::RenameComponent()
{
try
{
// Initialize the NX Open C++ API environment
RenameComponent::theSession = NXOpen::Session::GetSession();
RenameComponent::theUI = UI::GetUI();
theDlxFileName = "RenameComponent.dlx";
theDialog = RenameComponent::theUI->CreateDialog(theDlxFileName);
// Registration of callback functions
theDialog->AddApplyHandler(make_callback(this, &RenameComponent::apply_cb));
theDialog->AddOkHandler(make_callback(this, &RenameComponent::ok_cb));
theDialog->AddUpdateHandler(make_callback(this, &RenameComponent::update_cb));
theDialog->AddFilterHandler(make_callback(this, &RenameComponent::filter_cb));
theDialog->AddInitializeHandler(make_callback(this, &RenameComponent::initialize_cb));
theDialog->AddDialogShownHandler(make_callback(this, &RenameComponent::dialogShown_cb));
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
throw;
}
}

//------------------------------------------------------------------------------
// Destructor for NX Styler class
//------------------------------------------------------------------------------
RenameComponent::~RenameComponent()
{
if (theDialog != NULL)
{
delete theDialog;
theDialog = NULL;
}
}
//------------------------------- DIALOG LAUNCHING ---------------------------------
//
// Before invoking this application one needs to open any part/empty part in NX
// because of the behavior of the blocks.
//
// Make sure the dlx file is in one of the following locations:
// 1.) From where NX session is launched
// 2.) $UGII_USER_DIR/application
// 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly
// recommended. This variable is set to a full directory path to a file
// containing a list of root directories for all custom applications.
// e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_ROOT_DIR\menus\custom_dirs.dat
//
// You can create the dialog using one of the following way:
//
// 1. USER EXIT
//
// 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide"
// 2) Invoke the Shared Library through File->Execute->NX Open menu.
//
//------------------------------------------------------------------------------
extern "C" DllExport void ufusr(char *param, int *retcod, int param_len)
{
RenameComponent *theRenameComponent = NULL;
try
{
theRenameComponent = new RenameComponent();
// The following method shows the dialog immediately
theRenameComponent->Show();
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
if(theRenameComponent != NULL)
{
delete theRenameComponent;
theRenameComponent = NULL;
}
}

//------------------------------------------------------------------------------
// This method specifies how a shared image is unloaded from memory
// within NX. This method gives you the capability to unload an
// internal NX Open application or user exit from NX. Specify any
// one of the three constants as a return value to determine the type
// of unload to perform:
//
//
// Immediately : unload the library as soon as the automation program has completed
// Explicitly : unload the library from the "Unload Shared Image" dialog
// AtTermination : unload the library when the NX session terminates
//
//
// NOTE: A program which associates NX Open applications with the menubar
// MUST NOT use this option since it will UNLOAD your NX Open application image
// from the menubar.
//------------------------------------------------------------------------------
extern "C" DllExport int ufusr_ask_unload()
{
//return (int)Session::LibraryUnloadOptionExplicitly;
return (int)Session::LibraryUnloadOptionImmediately;
//return (int)Session::LibraryUnloadOptionAtTermination;
}

//------------------------------------------------------------------------------
// Following method cleanup any housekeeping chores that may be needed.
// This method is automatically called by NX.
//------------------------------------------------------------------------------
extern "C" DllExport void ufusr_cleanup(void)
{
try
{
//---- Enter your callback code here -----
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

int RenameComponent::Show()
{
try
{
theDialog->Show();
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return 0;
}

//------------------------------------------------------------------------------
//---------------------Block UI Styler Callback Functions--------------------------
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//Callback Name: initialize_cb
//------------------------------------------------------------------------------
void RenameComponent::initialize_cb()
{
try
{
group01 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group01"));
treeList = dynamic_cast<NXOpen::BlockStyler::Tree*>(theDialog->TopBlock()->FindBlock("treeList"));
group02 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group02"));
compDisplay = dynamic_cast<NXOpen::BlockStyler::Enumeration*>(theDialog->TopBlock()->FindBlock("compDisplay"));
group03 = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group03"));
selComponent = dynamic_cast<NXOpen::BlockStyler::SelectObject*>(theDialog->TopBlock()->FindBlock("selComponent"));
enum0 = dynamic_cast<NXOpen::BlockStyler::Enumeration*>(theDialog->TopBlock()->FindBlock("enum0"));
stringOriginal = dynamic_cast<NXOpen::BlockStyler::StringBlock*>(theDialog->TopBlock()->FindBlock("stringOriginal"));
stringPath = dynamic_cast<NXOpen::BlockStyler::StringBlock*>(theDialog->TopBlock()->FindBlock("stringPath"));
toggle0 = dynamic_cast<NXOpen::BlockStyler::Toggle*>(theDialog->TopBlock()->FindBlock("toggle0"));
stringNew = dynamic_cast<NXOpen::BlockStyler::StringBlock*>(theDialog->TopBlock()->FindBlock("stringNew"));
button0 = dynamic_cast<NXOpen::BlockStyler::Button*>(theDialog->TopBlock()->FindBlock("button0"));
//------------------------------------------------------------------------------
//用户代码
//------------------------------------------------------------------------------
treeList->SetOnSelectHandler(make_callback(this, &RenameComponent::OnSelectCallback));
//------------------------------------------------------------------------------

drawAll = false;

//设置选择掩码,只选择组件
NXOpen::Selection::SelectionAction action = Selection::SelectionActionClearAndEnableSpecific;
std::vector<NXOpen::Selection::MaskTriple>selectionMask_array(2);
selectionMask_array[0].Type = UF_component_type ;
selectionMask_array[0].Subtype = UF_component_subtype ;
selectionMask_array[1].Type = UF_component_type;
selectionMask_array[1].Subtype = UF_part_occurrence_subtype;

NXOpen::BlockStyler::PropertyList *selComponentProps = selComponent->GetProperties();
selComponentProps->SetSelectionFilter("SelectionFilter",action,selectionMask_array);
delete selComponentProps;
selComponentProps = NULL;
//设置控件显示
group01->SetShow(true);
group02->SetShow(false);
//设置group01折叠
group01->SetExpanded(false);
//设置树列表高度
treeList->SetHeight(300);
toggle0->SetValue(true);
//设置按键显示内容
button0->GetProperties()->SetString("Label","制作:Alan Huange QQ:185266370"); //修改按钮显示的内容
//设置enum0默认值
enum0->GetProperties()->SetEnum("Value", 0 );


}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

//------------------------------------------------------------------------------
//Callback Name: dialogShown_cb
//This callback is executed just before the dialog launch. Thus any value set
//here will take precedence and dialog will be launched showing that value.
//------------------------------------------------------------------------------

//循环遍历组装组件并填充树列表
void RenameComponent::PopulateTree(NXOpen::Assemblies::Component *component)
{
std::vector<Component *> childComponent = component->GetChildren();
int childComponentCount = childComponent.size();
for(int i=0; i<childComponentCount; ++i)
{
BlockStyler::Node *node = treeList->CreateNode(childComponent[i]->Name());
NXOpen::DataContainer *nodeData = node->GetNodeData();
nodeData->AddTaggedObject("Data",childComponent[i]);
treeNodes.push_back(node);
delete nodeData;
nodeData = NULL;

node->SetForegroundColor(198);
treeList->InsertNode(node,parentNode,NULL,treeList->NodeInsertOptionLast);
parentNode = node;
PopulateTree(childComponent[i]);
parentNode = node->ParentNode();
}

parentNode->Expand(Node::ExpandOptionExpand);
}

//执行部分清理并关闭高亮显示
void RenameComponent::PartCleanup()
{
try
{
NXOpen::PartCleanup *partCleanup1;
partCleanup1 = theSession->NewPartCleanup();
partCleanup1->SetTurnOffHighlighting(true);
partCleanup1->DoCleanup();
delete partCleanup1;
partCleanup1 = NULL;
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

//突出显示所选的组件
void RenameComponent::HighlightComponent(std::vector<NXOpen::TaggedObject *>&selObjectData, bool highlight)
{
try
{
//---- Enter your callback code here -----
int selObjectCount = selObjectData.size();

for(int i=0; i<selObjectCount; ++i)
{
NXOpen::Assemblies::Component *component = dynamic_cast<NXOpen::Assemblies::Component *> (selObjectData[i]);

if(!component)
continue;

highlight?component->Highlight():component->Unhighlight();

if(drawAll)
{
ComponentAssembly *owner =component->DirectOwner();//获取组件的父程序集
Component *mapped = owner->MapComponentFromParent(component);//获取该组件的其他情况
ComponentAssembly *topOwner = theSession->Parts()->Display()->ComponentAssembly();//获取组件的根部分

std::vector<Component *>mappedBack = topOwner->MapComponentsFromSubassembly(mapped);//返回出现的组件


int mappedBackCount = mappedBack.size();
for(int i=0; i<mappedBackCount; ++i)
{
highlight?mappedBack[i]->Highlight():mappedBack[i]->Unhighlight();

 

}
}
}
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

 

//获取组件的出现次数
std::vector<NXOpen::TaggedObject *>RenameComponent::GetComponentOccurences(std::vector<NXOpen::Assemblies::Component *>&assemblyComponent)
{
std::vector<NXOpen::TaggedObject *>componentOccurences ;
try
{
int assemblyComponentCount = assemblyComponent.size();

for(int i=0; i<assemblyComponentCount; ++i)
{
ComponentAssembly *owner = assemblyComponent[i]->DirectOwner(); //获取组件的父程序集
Component *mapped = owner->MapComponentFromParent(assemblyComponent[i]); //获取该组件的其他情况
ComponentAssembly *topOwner = theSession->Parts()->Display()->ComponentAssembly();//获取组件的根部分

std::vector<Component *>mappedBack = topOwner->MapComponentsFromSubassembly(mapped);
for (std::vector<Component *>::iterator it = mappedBack.begin(); it != mappedBack.end(); ++it)
{
componentOccurences.push_back(*it);
}
}
}
catch(exception& ex)
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return componentOccurences;
}

//从选择对象块中获取所选对象的标记
std::vector<NXOpen::TaggedObject *>RenameComponent::GetSelectedObjects()
{
std::vector<NXOpen::TaggedObject *>selCompTags ;
try
{
NXOpen::BlockStyler::PropertyList *selCompProps =selComponent->GetProperties();
selCompTags = selCompProps->GetTaggedObjectVector("SelectedObjects");
delete selCompProps;
selCompProps = NULL;

 


}
catch(exception& ex)
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return selCompTags;
}

//从树列表中获取所选节点的标记
std::vector<NXOpen::TaggedObject *>RenameComponent::GetSelectedNodes()
{
std::vector<NXOpen::TaggedObject *>selNodeTags ;
try
{
std::vector<NXOpen::BlockStyler::Node *>selectedNodes = treeList->GetSelectedNodes();
int selectedNodesCount = selectedNodes.size();
for(int i=0; i<selectedNodesCount; ++i)
{
NXOpen::DataContainer *nodeData = selectedNodes[i]->GetNodeData();
selNodeTags.push_back(nodeData->GetTaggedObject("Data"));
}
}
catch(exception& ex)
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return selNodeTags;
}

//指定组件选择选项是“单个组件”还是“所有组件”
bool RenameComponent::IsSingleComponentSelection()
{
bool singleComponent = false;
try
{
NXOpen::BlockStyler::PropertyList *compDisplayProps = compDisplay->GetProperties();
NXString componentDisplayType = compDisplayProps->GetEnumAsString("Value");
delete compDisplayProps;
compDisplayProps = NULL;

if(!strcmp(componentDisplayType.GetText(),"Single Component"))
singleComponent = true;
}
catch(exception& ex)
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return singleComponent;
}

//根据IsSingleComponentSelection,选择是针对单个组件还是针对所有组件
void RenameComponent::ComponentSelection()
{
try
{
bool singleComponent = IsSingleComponentSelection();
std::vector<NXOpen::TaggedObject *>selObjectData = GetSelectedObjects();
std::vector<NXOpen::TaggedObject *>selNodeComps = GetSelectedNodes();

// Create a DisplayModification object to set the color
if (selObjectData.size()>0)
{
HighlightComponent(selObjectData,false);
drawAll = singleComponent?false:true;
HighlightComponent(selObjectData, true);
}
if (selNodeComps.size()>0)
{
HighlightComponent(selNodeComps,false);
drawAll = singleComponent?false:true;
HighlightComponent(selNodeComps, true);
}
}
catch(exception& ex)
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

 


void RenameComponent::dialogShown_cb()
{
try
{
//---- Enter your callback code here -----

//设置控件显示
group01->SetShow(true);
group02->SetShow(false);

//设置group01折叠
group01->SetExpanded(false);
//设置树列表高度
treeList->SetHeight(300);
toggle0->SetValue(true);

//设置enum0默认值
enum0->GetProperties()->SetEnum("Value", 0 );

treeList->InsertColumn(0, "Component Names", 240);
treeList->SetColumnResizePolicy(0, Tree::ColumnResizePolicyResizeWithTree); //ColumnResizePolicyConstantWidth 固定列宽ColumnResizePolicyResizeWithContents 列宽按树列表ColumnResizePolicyResizeWithTree

BasePart *basePart(theSession->Parts()->BaseWork());

//在树列表中创建节点,并将组件与节点数据关联起来。
if(basePart!=NULL)
{
NXOpen::Assemblies::Component *rootComponent = basePart->ComponentAssembly()->RootComponent();

if(rootComponent != NULL)
{
parentNode = treeList->CreateNode(rootComponent->DisplayName());
NXOpen::DataContainer *nodeData = parentNode->GetNodeData();
nodeData->AddTaggedObject("Data",rootComponent);

delete nodeData;
nodeData = NULL;

parentNode->SetForegroundColor(186);
treeList->InsertNode(parentNode,NULL,NULL,treeList->NodeInsertOptionAlwaysFirst);
parentNode->Expand(Node::ExpandOptionExpand);
PopulateTree(rootComponent);
}
else
{
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeInformation, "Opened part is not an assembly. Tree-list will be empty");
return;
}
}

}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

//------------------------------------------------------------------------------
//Callback Name: apply_cb
//------------------------------------------------------------------------------
int RenameComponent::apply_cb()
{
int errorCode = 0;
try
{
//用户代码
//遍历文件夹改名
filesearch(strDir, 0);

 


}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
errorCode = 1;
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return errorCode;
}

//------------------------------------------------------------------------------
//Callback Name: update_cb
//------------------------------------------------------------------------------
int RenameComponent::update_cb(NXOpen::BlockStyler::UIBlock* block)
{
try
{
if(block == compDisplay)
{
//---------Enter your code here-----------
//用户代码
//ComponentSelection();

}
else if(block == selComponent)
{
//---------Enter your code here-----------
//用户代码
PartCleanup();
ComponentSelection();
setUI();

}
else if(block == enum0)
{
//---------Enter your code here-----------
}
else if(block == stringOriginal)
{
//---------Enter your code here-----------

}
else if(block == stringPath)
{
//---------Enter your code here-----------

}
else if(block == toggle0)
{
//---------Enter your code here-----------
//获取开关控件
PropertyList* ToggleProps = toggle0->GetProperties();
int ToggleValue = ToggleProps->GetLogical("Value");
delete ToggleProps;
ToggleProps = NULL;

if ( ToggleValue == 1 )
{
stringNew->SetValue(OriginalName);

}

else if ( ToggleValue == 0 )

{
stringNew->SetValue("");

}

}
else if(block == stringNew)
{
//---------Enter your code here-----------
}
else if(block == button0)
{
//---------Enter your code here-----------
}
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return 0;
}

//------------------------------------------------------------------------------
//Callback Name: ok_cb
//------------------------------------------------------------------------------
int RenameComponent::ok_cb()
{
int errorCode = 0;
try
{
errorCode = apply_cb();
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
errorCode = 1;
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
return errorCode;
}

//------------------------------------------------------------------------------
//Callback Name: filter_cb
//------------------------------------------------------------------------------
int RenameComponent::filter_cb(NXOpen::BlockStyler::UIBlock* block, NXOpen::TaggedObject* selectObject)
{
return(UF_UI_SEL_ACCEPT);
}
//------------------------------------------------------------------------------
//Treelist specific callbacks
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//Function Name: GetBlockProperties
//Description: Returns the propertylist of the specified BlockID
//------------------------------------------------------------------------------
PropertyList* RenameComponent::GetBlockProperties(const char *blockID)
{
return theDialog->GetBlockProperties(blockID);
}

void RenameComponent::keyboardFocusNotify_cb(NXOpen::BlockStyler::UIBlock* block, bool focus)
{
try
{
//---- Enter your callback code here -----
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}
//------------------------------------------------------------------------------
//Treelist specific callbacks
//------------------------------------------------------------------------------
void RenameComponent::OnSelectCallback(NXOpen::BlockStyler::Tree *tree, NXOpen::BlockStyler::Node *, int columnID, bool selected)
{
try
{
//---- Enter your callback code here -----
if(selected == true)
{
PartCleanup();
ComponentSelection();
}
}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

//获取文件名和路径
string RenameComponent::NameOrPath(const char* Path, int Type)
{
//反向找位置,分割字符串(只读取文件夹路径)
string strPath = Path;
string strDir;
int nPos = strPath.find_last_of('\\');
if (string::npos != nPos)
{
strDir = strPath.substr(0, nPos);
}



//分割字符串(只读取part名字+后缀)
//方法2
int pos = strPath.find_last_of('\\');
string s1(strPath.substr(pos + 1));

//分割字符串(只读取part名)
string PartName(s1.substr(0, s1.find(".prt")));

if (Type == 1)
{
return PartName;//返回名字
}
else if (Type == 2)
{
return strDir;//返回文件夹路径
}
}

//遍历文件夹改名
void RenameComponent::filesearch(string path, int layer)
{
UF_initialize(); //入口

char msg[256] = "";
char msgg[256] = "";
struct _finddata_t filefind;
string f;
string curr = path + "\\*.*";
int done = 0, i, handle;
if ((handle = _findfirst(curr.c_str(), &filefind)) != -1)
{
while (!(done = _findnext(handle, &filefind)))
{
if (strcmp(filefind.name, "..") == 0)
continue;
for (i = 0; i < layer; i++)
printf("\t");
if ((_A_SUBDIR == filefind.attrib)) // 是目录
{
curr = path + "\\" + filefind.name;
sprintf(msg, "%s\n", curr.c_str());

filesearch(curr, layer + 1); // 递归遍历子目录
}
else // 是文件
{
sprintf(msg, "%s", filefind.name);
if (strlen(msg) > 4)
{
strncpy(msgg, msg + strlen(msg) - 4, 4);
if (strcmp(msgg, ".prt") == 0) // 文件格式
{
f = path + "\\" + filefind.name;
sprintf(msg, "%s\n", f.c_str());


//分割字符串(只读取part名)
string PartName = NameOrPath(f.c_str(), 1);
string PartPath = NameOrPath(f.c_str(), 2);

//分割字符串(只读取part名)
string PartName1 = NameOrPath(part_name, 1);

 

//找到名字相同的.prt文件
if (PartName == PartName1)
{

//获取新名字
PropertyList *stringNewProps = stringNew->GetProperties();
NXString thestringNew = stringNewProps->GetString("Value");
delete stringNewProps;
stringNewProps = NULL;

//转换
char NewName1[256];
sprintf(NewName1, "\\%s.prt", thestringNew.GetLocaleText()); //NXString字符串转char,必须用.GetLocaleText()
string NewName2 = NewName1;

//字符串拼接
string NewName = PartPath + NewName2;

//找到原部件,另存为新名字
Part *part1(dynamic_cast<Part *>(theSession->Parts()->FindObject(PartName)));
PartSaveStatus *partSaveStatus1;
partSaveStatus1 = part1->SaveAs(NewName);
delete partSaveStatus1;

//由对枚举值判断是否删除原组件
int EnumValue = enum0->GetProperties()->GetEnum("Value");

if ( EnumValue == 0 )
{
//删除旧名字的.prt文件
DeleteFile(f.c_str());
}
else if ( EnumValue == 1 )
{
theUI->NXMessageBox()->Show("提示", NXOpen::NXMessageBox::DialogTypeInformation, "请注意原文件没有删除");

}

}

}
}
}
}
_findclose(handle);
}

UF_terminate(); //终止
}


//设置
void RenameComponent::setUI()
{
try
{
//---- Enter your callback code here -----

UF_initialize(); //入口

//获取选择的组件
PropertyList* ComponentSelectProps = selComponent->GetProperties();
std::vector<NXOpen::TaggedObject *> theComponentSelect = ComponentSelectProps->GetTaggedObjectVector("SelectedObjects");
delete ComponentSelectProps;
ComponentSelectProps = NULL;

//获取装配部件的part名称
char refset_name[MAX_ENTITY_NAME_SIZE+1];
char instance_name[UF_CFI_MAX_FILE_NAME_SIZE];
double origin[3];
double csys_matrix[9];
double transform[4][4];
UF_ASSEM_ask_component_data(theComponentSelect[0]->Tag(), part_name, refset_name, instance_name, origin, csys_matrix, transform);
//转换
char part_name_fullpath[133];
sprintf(part_name_fullpath, "%s", part_name);
//分割字符串(只读取part名)
string PartName1 = NameOrPath(part_name_fullpath, 1);
sprintf(OriginalName, "%s", PartName1.c_str());

 

stringOriginal->SetValue(OriginalName);
stringPath->SetValue(part_name_fullpath);
stringNew->SetValue(OriginalName);


//获取开关控件
PropertyList* ToggleProps = toggle0->GetProperties();
int ToggleValue = ToggleProps->GetLogical("Value");
delete ToggleProps;
ToggleProps = NULL;

if ( ToggleValue == 1 )
{
stringNew->SetValue(OriginalName);

}

else if ( ToggleValue == 0 )

{
stringNew->SetValue("");

}


//获得当前显示部件.prt文件所在路径
char part_fspec[MAX_FSPEC_SIZE+1];
UF_PART_ask_part_name(UF_PART_ask_display_part(), part_fspec);

//获取文件夹路径
strDir = NameOrPath(part_fspec, 2);

//遍历文件夹
//filesearch(strDir, 0);


UF_terminate(); //终止

}
catch(exception& ex)
{
//---- Enter your exception handling code here -----
RenameComponent::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what());
}
}

 

 NXOpen 对选择的组件重命名

 

上一篇:Spring - 源码分析:Spring是如何把Bean注册到IOC容器中的?


下一篇:用jstl截取字符串