C#开发窗体,通过Visual Studio直接进行窗体创建即可。但要注意,C#对应的.net框架有两套:.net framework和.net core。
其中,.net framework版本需要对应CAD的版本。.net core不能用于cad二次开发。
大致的:
2007-2009 Framework2.0
2010-2011 Framework3.5
2012-2013 Framework4.0
如果在安装Visual Studio的时候没有安装.net framework,则在创建窗体项目的时候不会有.net framework选项,只提供默认的.net core选项。(即.net core窗体)。需要打开Visual Stutio安装程序添加安装.net framework框架。
在创建项目之后,C#默认的窗体项目启动类是Program类:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
核心就在于Application.Run(new Form()) ,通过run方法,调用Form窗体,生成窗体。那么类似的,在CAD中调用插件生成的窗体也需要先new一下、run一下窗体。因为CAD二次开发的窗体,最终是在CAD中使用,所以需要调用CAD提供的一些API支持。
如下,CAD提供的API支持:
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.Runtime;
导入这些API支持,则又需要加载部分DLL,相当于加载包。在VS解决方案中引用,并在解决方案的引用中点击选择 不加载到本地:
accoremgd.dll
accui.dll
acdbmgd.dll
acmgd.dll
新建一个类,通过assembly提供CommandClass支持。将这个新建类声明为一个独立模块。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.Runtime;
[assembly: CommandClass(typeof(SecondCADForm.ModalDialog))]
namespace SecondCADForm
{
class ModalDialog
{
[CommandMethod("ModalDialog")]
public void ShowModalDialog()
{
using (Form1 form = new Form1())
{//模态对话框 -> 当前窗体在最上方显示
Application.ShowModalDialog(form);
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(form.textBox1.Text);
}
}
[CommandMethod("ModelessDialog")]
public void ShowModalDialog1()
{//非模态。非模态可以理解为对话框和cad是平级的,并行的。模态则是当前只能有一个在使用
Form1 form = new Form1();
Application.ShowModelessDialog(form);
}
}
}
窗体的使用,分为两种:模态对话框、非模态对话框
模态对话框简单来说就是,当前对话框在没有关闭(最小化都不行)之前,一直保持在屏幕的最上端。此时无法使用其他的窗体或者CAD。
非模态对话框则可以理解为对话框和CAD是平级的两个东西。对话框、CAD可以随时切换。
在解决好窗体的生成之后,在解决方案中将项目生成,由exe修改为dll。CAD通过netload命令加载dll,再通过自己定义的(commandmethod中定义的)命令调用窗体。