如何在Visual Studio 2022开发的Visio插件中创建可停靠窗口?
在Visual Studio 2022中创建Visio Add-In可停靠窗口的可行方案
别用独立WinForm了,直接用Visio的自定义窗口API把你的窗体嵌入进去,这才是集成式可停靠窗口的正确路子。之前你看的VBA文档方向没错,只是要适配.NET Add-In的写法,具体步骤如下:
核心思路
不是单独显示Form,而是把WinForm嵌入到Visio创建的自定义可停靠窗口里,利用Visio.Windows.Add方法创建容器,再把你的窗体塞进去。具体代码实现
- 先确保项目引用了
Microsoft.Office.Interop.Visio程序集 - 在Add-In的
ThisAddIn_Startup事件里写代码:private void ThisAddIn_Startup(object sender, System.EventArgs e) { // 实例化你的自定义窗体 var myCustomForm = new MyCustomForm(); // 关键设置:取消顶级窗体属性,不然没法嵌入 myCustomForm.TopLevel = false; myCustomForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; myCustomForm.Dock = System.Windows.Forms.DockStyle.Fill; // 获取当前Visio应用实例 var visioApp = this.Application; // 创建可停靠的Visio窗口:类型选模具样式(支持停靠),初始放左侧,宽度300 var customWindow = visioApp.Windows.Add( Visio.VisWinTypes.visWinTypeStencil, Visio.VisWinTypes.visWinLeft, 300, 0, false ); // 把窗体嵌入到Visio窗口中 IntPtr hwnd = customWindow.WindowHandle32; Control visioWindowHost = Control.FromHandle(hwnd); visioWindowHost.Controls.Add(myCustomForm); myCustomForm.Show(); // 设置窗口标题 customWindow.Caption = "My Integrated Window"; }
- 先确保项目引用了
注意点
- 一定要把Form的
TopLevel设为false,这是嵌入的前提 - 窗口类型
visWinTypeStencil可以换成visWinTypeDrawing等,不同类型的停靠行为略有区别 - 如果想让窗口记住用户调整后的位置,调用
customWindow.SaveWindowState就能实现
- 一定要把Form的
踩坑排查
- 要是调用
Windows.Add报错,大概率是代码执行太早,等Visio完全启动后再调用 - 窗体布局尽量用Dock或Anchor,避免嵌入后控件显示错位
- 要是调用
内容的提问来源于stack exchange,提问作者Daniel Scerpa
相关产品推荐
相关产品推荐

