AutoCAD_2007_net二次開發(fā)(英文版)_第1頁
AutoCAD_2007_net二次開發(fā)(英文版)_第2頁
AutoCAD_2007_net二次開發(fā)(英文版)_第3頁
AutoCAD_2007_net二次開發(fā)(英文版)_第4頁
AutoCAD_2007_net二次開發(fā)(英文版)_第5頁
已閱讀5頁,還剩38頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、AutoCAD 2007 .NET API Training Labs - C#Table of ContentsAutoCAD 2007 .NET API Training Labs - C#1Lab 1 Hello World: Accessing ObjectARX .NET Wrappers1Create your first AutoCAD managed application2Connect to the AutoCAD Managed API AcMgd.dll and AcDbMgd.dll2Define your first command2Test in AutoCAD2

2、Lab 2 .NET AutoCAD Wizard and more with the Editor class3The AutoCAD Managed Application Wizard3Prompt for User Input3Prompt to obtain a geometric distance4Lab 3 Database Fundamentals: Creating our Employee Object4Add a command to create the Employee object5Handling Exceptions First look6Transaction

3、s, Exception Handling and Dispose7Finish up the Employee object7More about Transactions, Exception Handling and Dispose7Create a Layer for the Employee7Add color to the Employee8Create an explicit Employee Block8Create a Block Reference for the new Employee block9Visual Studio 2005 Using Keyword9Ext

4、ra credit questions:10Lab 4 Database Fundamentals Part 2: Adding Custom Data11Create a custom structure in the Named Objects Dictionary11Add an Xrecord to our new structure hold custom data12Add an XRecord for each Employee Block Reference Instance13Iterate Model Space to Count each Employee Object1

5、3Notes about the completed lab14Lab 5 User Interaction: Prompts and Selection16Prompts17Block Attributes17Modify CreateEmployee () for reuse17Modify CreateDivision() for reuse19Define the CREATE command to create the employee19Selection22Lab 6 More User Interface: Adding Custom Data22Custom Context

6、Menu23Modeless, Dockable Palette Window with Drag and Drop25Drag and Drop Support in the Modeless Form26Entity Picking from a Modal Form28Adding a Page to the AutoCAD Options Dialog30Extra credit: Setup the dialog so that the values within the Edit boxes automatically reflect the Shared Manager and

7、Division strings in AsdkClass1.32Lab 7 Handling Events in AutoCAD32Events in C#32Delegates Described32C# += and -= statements32Handling AutoCAD Events in .NET33Lab: Using event handlers to control AutoCAD behavior33Setup the new project34Create the first Document event handler (callback)34Create the

8、 Database event handler (callback)34Create the second Document event handler (callback)36Create the commands to register/disconnect the event handlers37Test the project37Extra credit: Add an additional callback which is triggered when the EMPLOYEE block reference “Name” attribute has been changed by

9、 the user.38Lab 1 Hello World: Accessing ObjectARX .NET WrappersIn this lab, we will use Visual Studio .NET and create a new Class Library project. This project will create a .NET dll that can be loaded into AutoCAD. It will add a new command to AutoCAD named “HelloWorld”. When the user runs the com

10、mand, the text “Hello World” will be printed on the command line. Create your first AutoCAD managed application1) Launch Visual Studio and then select File> New> Project. In the New Project dialog select Visual C# Projects for the Project Type. Select “Class Library” template. Make the name “L

11、ab1” and set the location where you want the project to be created. Select OK to create the project.2) If the solution explorer is not visible in visual studio, you may turn it on by going to “View” menu and selecting “Solution Explorer”. This view will allow us to browse through files in the projec

12、t and add references to managed or COM Interop assemblies. Open Class1.vb that was added by the NET wizard by double-clicking on it in the solution explorer. 3) In Class1.cs notice that a public class was automatically created. We will add our command to this class. To do this we need to use classes

13、 in the AutoCAD .NET managed wrappers. These wrappers are contained in two managed modules. To add references to these modules, right click on “References” in the solution Explorer and select “Add Reference”. In the “Add Reference” dialog select “Browse”. Select “Look in” and navigate to the AutoCAD

14、 2007 directory. (C:Program FilesAutoCAD 2007) Find “acdbmgd.dll” and select OK. Click “Browse” again then select “acmgd.dll” and click OK. Connect to the AutoCAD Managed API AcMgd.dll and AcDbMgd.dll4) Use the Object Browser to explore the classes available in these managed modules. (View > Obje

15、ct Browser. Expand the “AutoCAD .NET Managed Wrapper” (acmgd) object. Throughout the labs we will be using these classes. In this lab an instance of “Autodesk.AutoCAD.EditorInput.Editor” will be used to display text on the AutoCAD command line. Expand the “ObjectDBX .NET Managed Wrapper” (acdbmgd) o

16、bject. The classes in this object will be used to access and edit entities in the AutoCAD drawing. 5) Now that we have the classes referenced we can import them. At the top of Class1.cs above the declaration of Class1 import the ApplicationServices, EditorInput and Runtime namespaces.i. using Autode

17、sk.AutoCAD.ApplicationServices;ii. using Autodesk.AutoCAD.EditorInput;iii. using Autodesk.AutoCAD.Runtime;Define your first command6) We will now add our command to Class1. To add a command that can be called in AutoCAD use the “CommandMethod” attribute. This attribute is provided by the Runtime nam

18、espace. Add the following attribute and function to Class1. i. CommandMethod("HelloWorld") ii. public void HelloWorld()iii. iv. 7) When the “HelloWorld” command is run in AutoCAD, the HelloWorld function will be called. In this function we will instantiate an instance of the editor class w

19、hich has methods for accessing the AutoCAD command line. (as well as selecting objects and other important features) . The editor for the active document in AutoCAD can be returned using the Application class. After the editor is created use the WriteMessage method to display “Hello World” on the co

20、mmand line. Add the following to the function HelloWorld:i. Editor ed = ii. Application.DocumentManager.MdiActiveDocument.Editor; iii. ed.WriteMessage("Hello World");8) Test in AutoCADTo test this in AutoCAD we can have Visual Studio start a session of AutoCAD. Right click on “Lab1” projec

21、t in Solution Explorer and select “Properties”. In the Lab1 Property Pages dialog select Debug, check Start External Program and use the ellipses button and browse to acad.exe. After changing this setting, hit F5 key to launch a session of AutoCAD.The “NETLOAD” command is used to load the managed ap

22、plication. Type NETLOAD on the AutoCAD command line to open the “Choose .NET Assembly” dialog. Browse to the location of “l(fā)ab1.dll” (.lab1bindebug), select it and then hit open.Enter “HellowWorld” on the command line. If all went well, the text “Hello World” should appear. Switch to Visual Studio an

23、d add a break point at the line: ed.WriteMessage(“Hello World”). Run the HelloWorld command in AutoCAD again and notice that you can step through code. If you have time you can explore the CommandMethod attribute. Notice that it has seven different flavors. We used the simplest one that only takes o

24、ne parameter, (the name of the command). You can use the other parameters to control how the command will work.*A point to note for future reference is that if you do get problems loading your application, use the fuslogvw.exe to diagnose.Back in Visual Studio try Exploring the CommandMethod attribu

25、te in the ObjectBrowser. Notice that it has seven different flavors. We used the simplest one that only takes one parameter, the name of the command. You can use the other parameters to control how the command will work. For example, you can specify command group name, global and local names, comman

26、d flag (for the context in which the command will run), and more. Lab 2 .NET AutoCAD Wizard and more with the Editor classThe AutoCAD Managed Application WizardIn the first lab we used a Class Library template and had to manually reference acdbmgd.dll and acmgd.dll. In this Lab we will use the AutoC

27、AD Managed C# Application Wizard to create the .NET project which will do this for us. You may first need to install the ObjectARX wizard before beginning this lab. (.ObjectARX 2007utilsObjARXWizArxWizards.msi) 1) Launch Visual Studio and then select File> New> Project. In the New Project dial

28、og select Visual C# Projects for the Project Types. Select the “AutoCAD Managed C# Project” template. Make the name “Lab2” and set the location where you want the project to be created. Select OK. The “AutoCAD Managed CSharp Application Wizard” will then appear. 'We will not be using unmanaged c

29、ode so leave the “Enable Unmanaged Debugging” unchecked. The “Registered Developer Symbol” will have the value entered when the Wizard was installed. Click finish to create the project. 2) Take a look at the project that the Wizard created. In Solution Explorer notice that acdbmgd and acmgd have bee

30、n referenced. In Class.cs “Autodesk.AutoCAD.Runtime” has been imported and the default public class name uses the registered developer symbol name. Also the wizard has added a CommandMethod attribute and a function that we can use for our command. Prompt for User Input3) In the previous lab we insta

31、ntiated an object of the “Autodesk.AutoCAD.EditorInput.Editor” class to write a message on the AutoCAD command prompt. In this lab we will use this class to prompt the user to select a point in the drawing and then display the x, y, z value that the user selected. As in the previous lab import Autod

32、esk.AutoCAD.ApplicationServices and Autodesk.AutoCAD.EditorInput. 4) Rename the string in the CommandMethod to something more meaningful like “selectPoint”. (The name of the function can remain the same). The PromptPointOptions class is passed into the editor.GetPoint method. At the beginning of the

33、 function instantiate an object using this class and set the string to “Select a point”. An instance of the class PromptPointResult is returned from the editor.GetPoint so we need to instantiate this as well.PromptPointOptions prPointOptions = new PromptPointOptions("Select a point"); Prom

34、ptPointResult prPointRes;5) Next get the editor object and use the GetPoint method passing in the PromptPointOptions object. Make the PromptPointResult object equal to the return value of the GetPoint method. We can then test the status of the PromptPointResult and return if it is not ok. prPointRes

35、 = ed.GetPoint(prPointOptions); if (prPointRes.Status != PromptStatus.OK) ed.WriteMessage("Error");6) Now that the PromptPointResult has a valid point we can print out the values to the command line. Use the WriteMessage method. The ToString method of the PromptPointResult.Value makes this

36、 easy:ed.WriteMessage("You selected point " + prPointRes.Value.ToString();7) Hit F5 to run to run a debug session of AutoCAD. (Notice that the wizard enabled debugging with acad.exe). Enter NETLOAD and navigate to the location of Lab2.dll and open it. On the command line enter the name you

37、 gave the command (selectpoint). At the select point prompt click somewhere in the drawing. If all is ok you will see the values of the selected point printed on the command line. In Class.cs put a break point on the line “ed.WriteMessage("Error");” and then run the selectpoint command aga

38、in. This time hit escape instead of selecting a point. The status of the PromptPointResult will not be OK so the if statement is true and “ed.WriteMessage("Error")” gets called. You may also observe that the point value is set to (0,0,0) in prPointRes. Prompt to obtain a geometric distance

39、8) Now we will add another command that will get the distance between two points. The wizard does not have a feature to add a command so we will need to do this manually. Create a new command in Class.cs named getdistance below the function that selects a point. As this has been covered several time

40、s the code is not listed here. Use the CommandMethod attribute and make the string for the command “getdistance” or something similar. In the function for the command use PromptDistanceOptions instead of PromptPointOptions. Also the result of GetDistance is a PromptDoubleResult so use this in place

41、of PromptPointResult:PromptDistanceOptions prDistOptions = newPromptDistanceOptions("Find distance, select first point:"); PromptDoubleResult prDistRes; prDistRes = ed.GetDistance(prDistOptions);9) As with the previous command test the status of the PromptDoubleResult. Then use the WriteMe

42、ssage method to display the values on the command line.if (prDistRes.Status != PromptStatus.OK) ed.WriteMessage("Error"); else ed.WriteMessage("The distance is: " + prDistRes.Value.ToString();Lab 3 Database Fundamentals: Creating our Employee ObjectBegin a new Lab3 project, or co

43、ntinue where you left off in your Lab2 code.In this lab, we will create an Employee object (1 circle, 1 ellipse and one MText object) within a Block Definition named EmployeeBlock which resides on EmployeeLayer which has a BlockReference associated with it inserted in Model Space.The lab will be exe

44、cuted in verifiable steps so that it is clear what each code section is meant to accomplish. The first step will demonstrate simply how to create a circle in Model Space. Each subsequent step will progress evenly until we have created our Block and Layer appropriately.The focus of this lab should be

45、 on the fundamentals of database access in AutoCAD. The major points are Transactions, ObjectIds, symbol tables (such as BlockTable and LayerTable) and object references. Other objects are used in conjunction with our steps such as Color, Point3d and Vector3d, but the focus should remain on the fund

46、amentals. A clear picture of the flavor of the .NET API should begin to take shape throughout this lab.Add a command to create the Employee object1) Create a command called CREATE, which calls the function CreateEmployee(). Within this function, add one circle to MODELSPACE at 10,10,0 with a radius

47、of 2.0:CommandMethod("CREATE")public void CreateEmployee() / First, declare the objects that we will use Circle circle; / This will be the circle we add to ModelSpace BlockTableRecord btr;/ To Add that circle, we must open ModelSpace BlockTable bt; / This example uses CurrentSpaceId, see n

48、ote below the next example of CreateEmployee / We encapsulate our entire database interaction in this / function with an object called a Transaction Transaction trans; / We delineate the boundaries of this interaction with / StartTransaction() member of TransactionManager trans = HostApplicationServ

49、ices.WorkingDatabase.TransactionManager.StartTransaction(); /Now, create the circlelook carefully at these arguments / Notice New for the Point3d and the static ZAxis circle = new Circle(new Point3d(10, 10, 0), Vector3d.ZAxis, 2); bt = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatab

50、ase.BlockTableId, OpenMode.ForRead); / Get the block table record using the current spaceId / notice we open for write btr = (BlockTableRecord)trans.GetObject(HostApplicationServices.WorkingDatabase.CurrentSpaceId,OpenMode.ForWrite ); / Now, use the btr reference to add our circle btr.AppendEntity(c

51、ircle); trans.AddNewlyCreatedDBObject(circle, true); /and make sure the transaction knows about it! / Once were done, we commit the transaction, / so that all our changes are saved trans.Commit(); / and dispose of the transaction, since were all done / (this is not a DB-resident object) trans.Dispos

52、e();Study the structure of this code block, and see the comments for details.Run this function to see it works. It should produce a white Circle of radius 2.0 at 10,10,0.2) We can save some typing cramps by declaring a Database variable instead HostApplicationServices.WorkingDatabase: Database db =

53、HostApplicationServices.WorkingDatabase;Use this variable in place of HostApplicationServices.WorkingDatabase() in your code.Handling Exceptions First look3) In the above code we are not using any exception handling, which is fundamental to a correct .NET application. We want to be in the habit of a

54、dding this code as we go. Lets add a try-catch-finally for this function.4) For compact code, we can spare ourselves the need to have a separate line for declaration and initialization for many of our variables. After these changes, you code should look like this:CommandMethod("CREATE")pub

55、lic void CREATEEMPLOYEE() Database db = HostApplicationServices.WorkingDatabase; Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Transaction trans = db.TransactionManager.StartTransaction(); try Circle circle = new Circle( new Point3d(10, 10, 0)

56、, Vector3d.ZAxis, 2); BlockTable bt = (BlockTable)trans.GetObject( db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject( HostApplicationServices.WorkingDatabase.CurrentSpaceId, OpenMode.ForWrite); btr.AppendEntity(circle); trans.AddNewlyCreatedDBObject(circle,

57、 true); trans.Commit(); catch ed.WriteMessage("Error "); finally trans.Dispose(); Notice how the ObjectId for Model Space is found using the CurrentSpaceId property of the WorkingDatabase. If Paper Space was current the ObjectId would not be the Model Space BlockTableRecord ObjectId. To ensure that the Model Space BlockTableRecord is opened use the ModelSpace BlockTableRecord field to get the ModelSpace ObjectId:BlockTableRecord btr =(BlockTableRecord)trans.GetObject(btBlockTableRecord.ModelSpace, OpenMode.ForWrite); Transactions, Exception Handling and DisposeSee here that th

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論