基於Visual C#的AutoCAD開發——執行個體1 基本例子

來源:互聯網
上載者:User

執行個體1 基本例子

 

1、建立項目

啟動Visual Studio 2005,建立一個項目,命名為“CAD開發”,如下圖所示:

2、添加引用

添加AutoCAD的引用AutoCAD 2007 Type Library和AutoCAD/ObjectDBX Common 17.0 Type Library,如下圖所示:

3、全域變數定義

在全域變數中定義如下:

        Autodesk.AutoCAD.Interop.AcadApplication AcadApp;

        Autodesk.AutoCAD.Interop.AcadDocument AcadDoc;

其中,AcadApplication是CAD對象介面,AcadDocument是CAD檔案。

4、開啟CAD檔案

添加一個按鈕,為按鈕添加如下代碼,實現開啟一個CAD檔案的功能:

        private void button1_Click(object sender, EventArgs e)

        {

            OpenFileDialog pOpenDG = new OpenFileDialog();

            pOpenDG.ShowDialog();

            string filePath = pOpenDG.FileName;

            AcadApp = new AcadApplication();

            AcadApp.Application.Visible = true;

            AcadDoc = AcadApp.Documents.Open(filePath,null,null);

        }

程式運行結果如下圖所示:

 

如果沒有語句“AcadApp.Application.Visible = true;”則無法顯示CAD軟體介面,只能啟動CAD在後台。通過“AcadApp = new AcadApplication();”是建立一個新的CAD對象,但是並不是每次都需要建立CAD對象,如CAD對象已經存在時就不需要再建立CAD對象。

5、定義啟動CAD對象的函數

定義一個啟動CAD對象的函數“啟動CAD()”,代碼如下:

        private void 啟動CAD()

        {

            try

            {

                AcadApp = (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");

                AcadDoc = AcadApp.ActiveDocument;

            }

            catch

            {

                OpenFileDialog pOpenDG = new OpenFileDialog();

                pOpenDG.Filter = "CAD檔案(*.dwg)|*.dwg|CAD圖形檔案(*.dxf)|*.dxf";

                pOpenDG.Title = "開啟CAD檔案";

                pOpenDG.ShowDialog();

 

                string filePath = pOpenDG.FileName;

                if (filePath == "")

                {

                    MessageBox.Show("選擇CAD檔案無效。", "檔案無效。");

                    Application.Exit();

                }

                AcadApp = new AcadApplication();

                AcadDoc = AcadApp.Documents.Open(filePath, null, null);

            }

            AcadApp.Application.Visible = true;

            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);

        }

其中“Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);”是使得CAD對象在最前面,要調用該函數還需要添加引用“Microsoft.VisualBasic”,如下圖所示:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.