找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 1999|回复: 6

[分享] Drive AutoCAD with Code

[复制链接]

已领礼包: 859个

财富等级: 财运亨通

发表于 2014-6-23 21:17:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Pluggable PaletteSet

In ObjectARX .NET API, AutoCAD.Windows.PaletteSet class makes creating dockable floating winidow in AutoCAD a pretty easy thing to do. Many AutoCAD programmers use PaletteSet as a UI container to host a series of Palettes (Windows Form User Controls, usually).

Prior to AutoCAD 2009, PaletteSet is sealed class, e.g. it cannot be inherited as a base class to derive your own custom PaletteSet. Since AutoCAD 2009, PaletteSet class is not sealed any more. This opens a possiblity for our AutoCAD programmer to create a custom, generic PaletteSet UI container once, and develop pluggable palette based on business need and plug into the PaletteSet when needed (without any code change to the PaletteSet).

In this article, I'll show how to use interface to define a pluggable PaletteSet. Interface is commonly used to define a set operations/properties for different classes to implement. It is one of the OO programming basic concept and used in .NET programming very often. However, there are many AutoCAD programmers who may not be a professional software developers and may too focused on AutoCAD API itself and did not explore some "advanced" programming technique enough, such as using "Interface" to simplify development tasks.

For this article, I demonstrate how to use Interface to create a pluggable PaletteSet. In Visual Stadio 2008, I started a class library project called MyPaletteSet, which includes 3 code files.

First code file is a interface that defines Palette that will be hosted in the pluggable PaletteSet: IThePalette. Later, when creating a Win Form UserControl as Palette, the UserControl will implement the interface. This, no matter how do you design your UserControls and how different they would be, to the hosting PaletteSet, they all are IThePalette. That is, the hosting PaletteSet does not have knowledge of each individual UserControl it hosts, as long as the UserControl is an IThePalette.

Here is the code:

namespace MyPaletteSet
{
    public interface IThePalette
    {
        ThePaletteSet PaletteSet { set; get; }
        string PaletteName { get; }
        void Close();
        void ClosePaletteSet();
    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:18:08 | 显示全部楼层
Second code file is the custom PaletteSet, derived from Autodesk.AutoCAD.Windows.PaletteSet. As aforementioned, it is only possible when you use AutoCAD 2009 or later.

Here is the code:

using System;
using System.Drawing;using System.Collections.Generic;

using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
namespace MyPaletteSet{
    public class ThePaletteSet : PaletteSet    {
        private static Guid _guid =             new Guid("B9169E25-3EC1-442F-B518-46B2DA174A2F");
        private DocumentCollection _dwgManager = null;        private List<IThePalette> _paltettes = new List<IThePalette>();

        public event DocumentCollectionEventHandler DwgBecameCurrent;

        public ThePaletteSet()
            : base("ThePaletteSet",null, _guid)        {
            this.Style = PaletteSetStyles.ShowAutoHideButton |                PaletteSetStyles.ShowCloseButton |
                PaletteSetStyles.Snappable;
            this.Opacity = 100;            this.Dock = DockSides.None;
            this.DockEnabled = DockSides.None;
            this.Size = new Size(500, 400);            this.MinimumSize = new Size(250, 200);

            _dwgManager = Autodesk.AutoCAD.ApplicationServices
                .Application.DocumentManager;
          //Handle DocumentCollection events to bubble up the event for IThePalette            _dwgManager.DocumentBecameCurrent +=
                new DocumentCollectionEventHandler(_dwgManager_DocumentBecameCurrent);        }

        private void _dwgManager_DocumentBecameCurrent(
            object sender, DocumentCollectionEventArgs e)        {
            if (DwgBecameCurrent != null)            {
                DwgBecameCurrent(this, e);            }
        }
        public void AddPalette(IThePalette palette)        {
            bool exists = false;            foreach (IThePalette plt in _paltettes)
            {                if (plt.PaletteName.ToUpper() == palette.PaletteName.ToUpper())
                {                    exists = true;
                    break;                }
            }
            if (!exists)            {
                System.Windows.Forms.Control ctl =                     palette as System.Windows.Forms.Control;

                //Add to paletteset
                this.Add(palette.PaletteName, ctl);
                _paltettes.Add(palette);                palette.PaletteSet = this;
            }        }

        public void RemovePalette(string paletteName)
        {            if (_paltettes.Count == 0) return;

            for (int i = 0; i < _paltettes.Count; i++)
            {                if (_paltettes.PaletteName.ToUpper() == paletteName.ToUpper())
                {                    System.Windows.Forms.Control ctl =
                        _paltettes as System.Windows.Forms.Control;
                    this.Remove(i);                    _paltettes.RemoveAt(i);

                    ctl.Dispose();

                    if (_paltettes.Count == 0) this.Visible = false;

                    return;
                }            }
        }
        public void ActivatePalette(string paletteName)        {
            if (_paltettes.Count == 0) return;
            for (int i = 0; i < _paltettes.Count; i++)            {
                if (_paltettes.PaletteName.ToUpper() == paletteName.ToUpper())                {
                    this.Activate(i);                    return;
                }            }
        }    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:21:09 | 显示全部楼层
Pay attention to this line of code:

[font=Arial, Helvetica, sans-serif]public event DocumentCollectionEventHandler DwgBecameCurrent;[/font]

and this line of code:

_[font=Arial, Helvetica, sans-serif]dwgManager.DocumentBecameCurrent += new .......[/font]

Some of your Palettes may be designed to handle drawing based data. Since PaletteSet is a floating/modeless window, when current drawing changed in AutoCAD, the data shown in certain palette should be refreshed because of current drawing change (like AutoCAD's "Properties" window). Therefore, the this type of palette must be able to handle various events originally raised by DocumentCollection. So, here I simply handle the DocumentCollection events in the custom PaletteSet and bubble the events up. It is up to the individual Palette to subscribe the events when necessary. To simplfy the example, I only handle and raise the DocumentBecameCurrent event. In real production code, we could bubble up all the DocumentCollection events. The third code file is contains a static help method to create an instance of the custom PaletteSet. Here is the code:


using Autodesk.AutoCAD.Runtime;

[assembly: ExtensionApplication(typeof(MyPaletteSet.ThePaletteSetInitializer))]

namespace MyPaletteSet
{
    public class ThePaletteSetInitializer : IExtensionApplication
    {
        private static ThePaletteSet _paletteSet = null;

        public void Initialize()
        {
            //If necessary, add some code
        }

        public void Terminate()
        {
            if (_paletteSet != null) _paletteSet.Dispose();
        }

        public static ThePaletteSet CreateThePaltetteSet(IThePalette palette)
        {
            if (_paletteSet == null)
            {
                _paletteSet = new ThePaletteSet();
            }

            //Add palette to the PaletteSet
            _paletteSet.AddPalette(palette);

            return _paletteSet;
        }

        public static ThePaletteSet CreateThePaltetteSet()
        {
            if (_paletteSet == null)
            {
                _paletteSet = new ThePaletteSet();
            }

            return _paletteSet;
        }
    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:21:36 | 显示全部楼层

That's it. Now we have a generic, pluggable PaletteSet. Build the project. From now on, when you want to build a suite of your own tools that have UI to be hosted in a PaletteSet, you can focus to the development of the Palette (Win Form UserControl) and never need to update the PaletteSet host and redeploy it. Let's see a couple of sample palettes. Sample 1: FirstPalette. Start a new class library command. It can be in the same solution as the "MyPaletteSet". But to better understand the "pluggable" nature, it is recommended to do this project in different solution. This will show that you can really focus on developing your Palette without having to update the PaletteSet at all. Once the project created, set reference to the DLL generated in "MyPaletteSet" project (MyPaletteSet.dll). Add a Win Form UserControl, called FirstPalette. It looks like:


Here is the code of the UserControl:
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:22:47 | 显示全部楼层
using System;
using System.Windows.Forms;
using Autodesk.AutoCAD.ApplicationServices;
using MyPaletteSet;

namespace FirstPaletteTool
{
    public partial class FirstPalette : UserControl, IThePalette
    {
        private ThePaletteSet _parent = null;

        public FirstPalette()
        {
            InitializeComponent();

            Document dwg = Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;
            if (dwg != null) txtFileName.Text = dwg.Name;
        }

        #region IThePalette Members

        public string PaletteName
        {
            get { return "First Palette"; }
        }

        public ThePaletteSet PaletteSet
        {
            get
            {
                return _parent;
            }
            set
            {
                _parent = value;
                _parent.DwgBecameCurrent +=
                    new DocumentCollectionEventHandler(
                        _parent_DwgBecameCurrent);
            }
        }

        void _parent_DwgBecameCurrent(object sender,
            DocumentCollectionEventArgs e)
        {
            txtFileName.Text = e.Document.Name;
        }

        public void Close()
        {
            if (_parent != null)
            {
                _parent.RemovePalette(this.PaletteName);
            }
        }

        public void ClosePaletteSet()
        {
            if (_parent != null) _parent.Visible = false;
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            this.ClosePaletteSet();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:23:43 | 显示全部楼层
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;

using MyPaletteSet;

[assembly: CommandClass(typeof(FirstPaletteTool.FirstPaletteCommand))]

namespace FirstPaletteTool
{
    public class FirstPaletteCommand
    {
        private static ThePaletteSet _pltSet;

        [CommandMethod("StartFirst", CommandFlags.Session)]
        public static void RunThisMethod()
        {
            Document dwg = Application.DocumentManager.MdiActiveDocument;

            try
            {
                FirstPalette plt = new FirstPalette();

                _pltSet = MyPaletteSet.
                    ThePaletteSetInitializer.CreateThePaltetteSet(plt);
                _pltSet.Visible = true;
                _pltSet.ActivatePalette(plt.PaletteName);
            }
            catch(System.Exception ex)
            {
                dwg.Editor.WriteMessage("\nError: " + ex.Message);
            }
        }
    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-23 21:24:51 | 显示全部楼层
Since I want this palette to show per-drawing based data, thus, I make this palette subscribe event "DwgBecameCurrent" raised by the hosting PaletteSet (MyPaletteSet). As you can see, no matter what UI components you place onto this palette (UserControl) and what code logic you will let this palette to execute, you can plug the palette into a common PaletteSet easily. New, let me create another palette: SecondPalette. Start a new class library project, called "SecondPaletteTool", set reference to "MyPaletteSet.dll". Add a Win Form UserControl, which looks like:



Its code is here:

Code Snippet
  • using System;
  • using System.Windows.Forms;
  • using MyPaletteSet;
  • namespace SecondPaletteTool
  • {
  •     public partial class SecondPalette : UserControl, IThePalette
  •     {
  •         private ThePaletteSet _parent = null;
  •         public SecondPalette()
  •         {
  •             InitializeComponent();
  •         }
  •         #region IThePalette Members
  •         public ThePaletteSet PaletteSet
  •         {
  •             get
  •             {
  •                 return _parent;
  •             }
  •             set
  •             {
  •                 _parent = value;
  •             }
  •         }
  •         public string PaletteName
  •         {
  •             get { return "Second Palette"; }
  •         }
  •         public void Close()
  •         {
  •             if (_parent != null)
  •             {
  •                 _parent.RemovePalette(this.PaletteName);
  •             }
  •         }
  •         public void ClosePaletteSet()
  •         {
  •             if (_parent != null) _parent.Visible = false;
  •         }
  •         #endregion
  •         private void button1_Click(object sender, EventArgs e)
  •         {
  •             this.Close();
  •         }
  •         private void button2_Click(object sender, EventArgs e)
  •         {
  •             this.ClosePaletteSet();
  •         }
  •     }
  • }



Notice that this palette does not subscribe event raised by hosting PaletteSet. Add a class into the project: SecondPaletteCommand:

Code Snippet
  • using Autodesk.AutoCAD.ApplicationServices;
  • using Autodesk.AutoCAD.Runtime;
  • using MyPaletteSet;
  • [assembly: CommandClass(typeof(SecondPaletteTool.SecondPaletteCommand))]
  • namespace SecondPaletteTool
  • {
  •     public class SecondPaletteCommand
  •     {
  •         private static ThePaletteSet _pltSet;
  •         [CommandMethod("StartSecond", CommandFlags.Session)]
  •         public static void RunThisMethod()
  •         {
  •             Document dwg = Application.DocumentManager.MdiActiveDocument;
  •             try
  •             {
  •                 SecondPalette plt = new SecondPalette();
  •                 _pltSet = MyPaletteSet.
  •                     ThePaletteSetInitializer.CreateThePaltetteSet(plt);
  •                 _pltSet.Visible = true;
  •                 _pltSet.ActivatePalette(plt.PaletteName);
  •             }
  •             catch (System.Exception ex)
  •             {
  •                 dwg.Editor.WriteMessage("\nError: " + ex.Message);
  •             }
  •         }
  •     }
  • }



As you can see, no matter how different the second palette from the first one, it can be plugged into MyPaletteSet in the same way, because, to MyPaletteSet, these 2 palettes are the same type: IMyPalette.

Now, start AutoCAD and "NETLOAD" the 2 palette projects (e.g. load FirstPaletteTool.dll and SecondPaletteTool.dll separately, as if the 2 DLLs are deployed and loaded separately). Enter command "StartFirst" and/or "StartSecond". You can see the corresponding palette will be shown in a common PaletteSet. If you open more than one drawings in AutoCAD and switch the active drawing, you can see the file name shown on the "First Palette" changes accordingly, because this palette handles DwgBecameCurrent event raised by the hosting PaletteSet.

From now on, whenever I want to develop a new AutoCAD tool that would have a modeless window as UI, I can go ahead to develop the UI as Win Form UserControl. Once it is done, I can simply plug it into the common hosting PaletteSet. Since the newly developed palette is in its own project, it can be deployed independently to all existing palettes, yet they are hosted in the same PaletteSet.

In the FirstPalette, I have to add "using Autodesk.AutoCAD.ApplicationServices;" because the palette has to comsume DocumentCollectionEventArgs in the DwgBecameCurrent event handler. In real development code, it is best practice to not let the UserControl to be tied to AutoCAD's dll. In this case, it is better to define my own custom EvenArgs and my own custom EventHandler in the MyPaletteSet project and use them to bubble up the various DocumentCollection events.
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|申请友链|Archiver|手机版|小黑屋|辽公网安备|晓东CAD家园 ( 辽ICP备15016793号 )

GMT+8, 2024-11-17 22:49 , Processed in 0.203842 second(s), 46 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表