如何为Inventor可停靠窗口添加按钮并绑定执行子程序?
重构Inventor不可停靠工具为可停靠窗口:添加按钮及绑定事件
一、现有可停靠窗口创建代码解析
你当前的代码实现了创建Inventor可停靠窗口并嵌入外部窗口的核心逻辑,但硬编码的hwnd需要替换为你现有工具界面的句柄。原代码如下:
Dim oUserInterfaceMgr As UserInterfaceManager Set oUserInterfaceMgr = ThisApplication.UserInterfaceManager ' Create a new dockable window Dim oWindow As DockableWindow Set oWindow = oUserInterfaceMgr.DockableWindows.Add("SampleClientId6", "TestWindowInternalName6", "Test Window6") ' Get the hwnd of the dialog to be added as a child ' CHANGE THIS VALUE! Dim hwnd As Long hwnd = 4851096 ' Add the dialog as a child to the dockable window oWindow.AddChild(hwnd) ' Don't allow docking to top and bottom oWindow.DisabledDockingStates = DockingStateEnum.kDockTop And DockingStateEnum.kDockBottom ' Make the window visible oWindow.Visible = True
二、添加按钮及绑定事件的完整实现
你的现有工具界面包含多个功能按钮,以下是将其重构为可停靠窗口的具体步骤:
1. 准备带功能按钮的VBA用户窗体(UserForm)
- 打开Inventor的VBA编辑器,插入一个
UserForm。 - 在UserForm上添加对应原工具的按钮(如“创建零件”“生成工程图”等)。
- 为每个按钮编写点击事件的处理子程序,示例:
Private Sub btnCreatePart_Click() ' 这里写入原工具中对应按钮的功能逻辑 Dim oPartDoc As PartDocument Set oPartDoc = ThisApplication.Documents.Add(kPartDocumentObject, , True) MsgBox "已创建新零件文档" End Sub Private Sub btnDrawDrawing_Click() ' 示例:生成工程图的逻辑 MsgBox "执行生成工程图操作" End Sub
2. 将UserForm嵌入可停靠窗口
修改原有的可停靠窗口创建代码,替换硬编码的hwnd为UserForm的句柄,确保UserForm以无模式方式加载:
Dim oUserInterfaceMgr As UserInterfaceManager Set oUserInterfaceMgr = ThisApplication.UserInterfaceManager ' 创建唯一标识的可停靠窗口 Dim oWindow As DockableWindow Set oWindow = oUserInterfaceMgr.DockableWindows.Add("MyInventorTool_ClientId", "MyInventorTool_InternalName", "我的Inventor工具") ' 加载UserForm(无模式,避免阻塞Inventor) UserForm1.Show vbModeless UserForm1.Visible = False ' 可选:嵌入前不显示独立窗口 ' 获取UserForm的句柄 Dim hwnd As Long hwnd = UserForm1.hWnd ' 将UserForm作为子窗口嵌入可停靠窗口 oWindow.AddChild hwnd ' 设置禁用的停靠位置(禁止上下停靠) oWindow.DisabledDockingStates = DockingStateEnum.kDockTop Or DockingStateEnum.kDockBottom ' 显示可停靠窗口 oWindow.Visible = True
3. 处理窗口生命周期(避免内存泄漏)
添加可停靠窗口的关闭事件监听,确保关闭窗口时释放UserForm资源:
' 在标准模块中声明全局可停靠窗口变量(带事件) Public WithEvents oDockWindow As DockableWindow ' 在创建窗口的代码中赋值 Set oDockWindow = oWindow ' 窗口关闭事件处理 Private Sub oDockWindow_OnClose() Unload UserForm1 End Sub
三、关键注意事项
- 确保UserForm的
ShowModal属性设为False(无模式),否则会阻塞Inventor的正常操作。 - 必须在UserForm显示后再获取句柄,否则会导致句柄获取失败。
- 可停靠窗口的
ClientId需保持唯一,避免与其他Inventor插件冲突。 - 测试时注意Inventor版本兼容性,不同版本的API可能存在细微差异。
内容的提问来源于stack exchange,提问作者Børge Vagn Birkebæk Truelsen
相关产品推荐
相关产品推荐

