Autodesk Official latest. NET tutorial (vi) (C # Edition)

Source: Internet
Author: User
Tags command line constructor finally block joins connect tostring try catch
Tutorial Chapter 6th more user interfaces: Adding custom data in this chapter, we will describe what the user interface section of the. NET API can do. We'll begin by introducing a custom context menu (shortcut menu). Next we will implement a modeless dockable panel (a real AutoCAD enhanced auxiliary window) to support drag-and-drop operations. Then we'll introduce the selection of entities through the modal form. Finally, we'll introduce the options dialog with AutoCAD to set the employee's default value. This chapter also describes the APIs related to the above content.   The first part of the custom context menu   So far, the code we write is only interoperable with the command line defined by the Commandmethod property. An AutoCAD. NET program can implement initialization at load time through a special class. This class only implements Iextensionapplication. NET interface and exposes a component-level attribute that defines a class as extensionapplication, you can respond to a one-time mount and unload event. Example: [Assembly:extensionapplication (typeof (Lab6_cs). ASDKCLASS1))]    public class asdkclass1:iextensionapplication   { 1) Now modify the AsdkClass1 class to implement the above interface. To implement this interface, you must implement the Initialize () and terminate () functions. Because we want to implement an interface, the functions in the interface are always defined as pure virtual.        public void Initialize ()       {          Addcontextmenu ();         Employeeoptions.addtabdialog ();     }               public void TeRminate ()       {     }  to join a custom context menu, we must define a ' Members of the Contextmenuextension ' class. This class is in the Autodesk.AutoCAD.Windows namespace. To use Contextmenuextension, we must initialize with the New keyword, assign a value to the necessary attributes, and invoke Application.adddefaultcontextmenuextension (). The context menu works by: For each menu item, we define a member function to handle the menu click event. We may pass. NET agent to implement the. We use the C # keyword + = and-= to determine which function to handle the event. Familiarize yourself with this design pattern as quickly as possible, because you will use a lot in C #. 2 Add a ' contextmenuextension ' member variable and the following two functions to add and remove custom menus. Please take a good look at the code to see what's going on.       void Addcontextmenu ()       {          try         {             M_contextmenu = new Contextmenuextension ();             m_contextmenu.title = "Acme Employee Menu";             Autodesk.AutoCAD.Windows.MenuItem mi;             mi = new Autodesk.AutoCAD.Windows.MenuItem ("Create Employee");             mi. Click +=  New EventHandler (Callbackonclick);             M_CONTEXTMENU.MENUITEMS.ADD (mi);                         Autodesk.AutoCAD.ApplicationServices.Application.AddDefaultContextMenuExtension (M_contextmenu);         }         catch          {        }      }       void Removecontextmenu ()       {          try         {             if (m_contextmenu!= null)              {               Autodesk.AutoCAD.ApplicationServices.Application.RemoveDefaultContextMenuExtension (M_contextmenu);                 M_contextmenu = null;            }        }          catch         {         }     }  Note that we use the ' callbackonclick ' function in our code. We want this function (which we haven't defined yet) to respond to menu item selection events. In our example, what we want to do is call our member function ' Create () '. Please add the following code.       void Callbackonclick (Object Sender, EventArgs e)       {          Create ();      }  Now, call the Addcontextmenu () function from Initialize (), and likewise, call Terminate () in Removecontextmenu (). Please run the code. Use Netload to load the compiled component, and then right-click in the blank space of AutoCAD ... You should be able to see the ' Acme ' shortcut menu. If you fail, you are doing the right thing. Why, then? Typically, the data in AutoCAD is stored in the document, and the commands that access the entity have the right to modify the document. When we run code to respond to context menu click events, we access the document from outside the command structure. When the code we invoked tried to modify the document by adding an employee, we ran into an error. The right thing to do is to lock the document, which can be done by using the document.lockdocument () command. 3 Modify Callbackonclick to lock the document:      void Callbackonclick (Object Sender, EventArgs e)        {         Documentlock Doclock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument ();          Create ();         doclock.dispose () ;     }  Note that we have retained a copy of the ' Documentlock ' object. To unlock the document, we just have to destroy the Documentlock object. Run the code again. You should see the shortcut menu now.   Part 2nd modeless dialog box, dockable panel for drag and drop to enable seamless linking of our user interface and AutoCAD, we want to use the same user interface structure wherever possible. This makes the application appear to be combined with AutoCADWell, and effectively reduce the duplication of code. A good example is the dockable panel in AutoCAD. Using the. NET API, we can create a simple form and put it in a panel. We can instantiate a custom ' Paletteset ' object to contain the form, and we can define the Paletteset as our favorite style. 4 Add a user control in the solution browser by right-clicking the project. Give it the name Modelessform. Using the Control Toolbox, add the Edit boxes and label controls as shown below. <!--[if!vml]--><!--[endif]-->  use the Properties window to set the properties of three edit boxes. Set the following:< first is the top edit box > (name)     = Tb_nametext = < Please enter a name > < the second edit box > (name) = Tb_ Divisiontext = sales < third edit box > (Name) = Tb_salarytext = < Please enter salary >   to instantiate a panel object using the. NET API. You have to instantiate the user Control object (modeless form) and the ' Paletteset ' object. Call the Paletteset member function add to pass the user control object. 5 Next, we'll add a command to create the panel. Add a function and Commandmethod property named CreatePalette to the class to define the command named "PALETTE". Take a look at the code block below. This is the code for the instantiation panel. PS = new Autodesk.AutoCAD.Windows.PaletteSet ("Test Palette Set");p S. MinimumSize = new System.Drawing.Size (300, 300); System.Windows.Forms.UserControl Myctrl = new Modelessform ();p S. ADD ("Test", Myctrl);p S. Visible = true; 6) Adds the above code to the CreatePalette () function. ' PS ' needs to be declared outside the function:      private Autodesk.AutoCAD.Windows.PaletteSeT ps;  the code that checks whether PS is null before the instantiation panel code of the function. Compile and run the project. Load the component in AutoCAD and run the ' PALETTE ' command to check if the panel is loaded. Use Paletteset.style to look at the Palettesetstyles object. For example: PS. Style = Palettesetstyles.showtabforsingle; We can also try properties such as transparency, such as:   PS. Opacity = 90;  Note: To use the Paletteset and Palettesetstyles objects, You have to add two namespaces Autodesk.AutoCAD.Windows and autodesk.autocad.windows.palette  before we go on, Let's perform a quick maintenance update: Please add the following members to the AsdkClass1 class:      public static string sdivisiondefault = "Sales";       public static string Sdivisionmanager = "Fiona Q. Farnsby";  These values will be used as default values for department and department managers. Because they are declared ' static ', they are instantiated only once in each program and instantiated when the component is loaded.   Part 2a Adding drag-and-drop support in modeless forms in this section, we'll add a value that allows us to create an employee by using the values of the edit box in the Panel form. When users drag from the panel to AutoCAD, they are prompted for a position that a new employee entity will use to create. 7 in order to support drag-and-drop, we first need an object to drag. Under the edit box, add a Label control named Label4, and set the text of the label to something suggestive (' Drag to Create Employee '). With this tag, we can handle drag and drop in AutoCAD. To capture when the drag event occurs, we have to know when the mouse starts. First, we want to register the event in the constructor of the class, as follows:         Label4.mousemove + = new SYSTEM.WINDOWS.FOrms. MouseEventHandler (label4_mousemove);  8) Add the following function declaration to the Modelessform class:      private void Label4_mousemove (object sender, System.Windows.Forms.MouseEventArgs e)       {          if (System.Windows.Forms.Control.MouseButtons = = System.Windows.Forms.MouseButtons.Left)          {            //Start DragDrop operation, Mydroptarget is called when the cursor Enters the AutoCAD view area.            Autodesk.AutoCAD.ApplicationServices.Application.DoDragDrop (this, this, System.Windows.Forms.DragDropEffects.All , new Mydroptarget ());        }     }  The event handler usually has 2 input parameters, an object class sender and an event-related parameter. For MouseMove, we have to do the same thing. Run this project and check to see if the function is invoked when the mouse passes through the text. We can also further know if the left mouse button is not pressed:         if (System.Windows.Forms.Control.MouseButtons = = System.Windows.Forms.MouseButtons.Left)          {         }  We need a way to detect when objects are dragged into AutoCAD. We can use. NET to implement the base class DropTarget. To use it, you just create a class that derives from the base class and implement the function you want. In our case, what we need is OnDrop (). 9 Add a class ' Mydroptarget ' derived from Autodesk.AutoCAD.Windows.DropTarget in the project. If you add this class to the ModelessForm.cs file, add the class to the Modelessform class.       override public void OnDrop (System.Windows.Forms.DragEventArgs e)     { }  in this function, we end up calling the ASDKCLASS1 members Createdivision () and Createemployee, passing in the value of the edit box in the Modelessform class. To implement this feature, we need a way to connect the Modelessform instance. The best way to do this is through DragEventArgs. But first we want to connect the mouse event to the Mydroptarget class. 10 Add the following code to the left mouse button (mousebuttons.left) processing function:   Autodesk.AutoCAD.ApplicationServices.Application.DoDragDrop (this, this, System.Windows.Forms.DragDropEffects.All , new Mydroptarget ());  Note that we passed in ' this ' two times. The first time is for the control parameter and the second is for incoming user custom data. Because we're passing in a modeles.An instance of the Sform class, so we can use it to get the value of the edit box when we drop it. 11) Back to the OnDrop processing function, let's use parameters to invoke the function that created the employee. First, add the code for the job tip. There is already code in Asdkclass1.create (), located in ' Get Employees coordinates ... '. Note below. Add this code to prompt for a position. 12 Next, get the Modelessform object that is passed into the DragEventArgs parameter:         modelessform CTRL = ( Modelessform) e.Data.GetData (typeof (Modelessform));  Please note how to force a parameter into an instance of typeof through the Modelessform keyword. 13) Use the above example to invoke ASDKCLASS1 member:         asdkclass1.createdivision (ctrl.tb_ Division.text, Asdkclass1.sdivisionmanager);         Asdkclass1.createemployee (Ctrl.tb_Name.Text, Ctrl.tb_Division.Text, Convert.todouble (Ctrl.tb_Salary.Text), Prposres.value);  Note: The AsdkClass1 method is not invoked through an instance of AsdkClass1, so the method must be declared as ' public static '. Because the public static method can only invoke other public static methods, you need to modify the methods in several ASDKCLASS1 classes to ' public static '. Please make the relevant changes (there should be at least 4 items to be modified). 14 Finally, because we are dealing with events outside of the AutoCAD command, we must again lock the document in the code where the database will be modified. Please add the code to lock the document and add the same method as the previous context menu. Compile, load, and run the component, using the Palette command. You should be able to create an employee by using a drag-and-drop operation。   Part III selecting Entities from a modal form the following sections of this chapter demonstrate the details of obtaining an employee instance selected by a user on the screen, and display the information in an edit box in a modal form. The focus of this section is to create a modal form and hide it when you perform a select action and the form loses focus. To get the employee's details, we'll use the Listemployee help function given at the end of chapter 4th. First, we need to create a form class. This class is a real form instead of the user control we created in Modelessform. 15 Create a Windows Forms class in the project. Call the ' Modalform ' class. Add the following three edit box controls and Label controls and two buttons to the form. <!--[if!vml]--><!--[endif]-->   uses the Properties window to set the properties of three edit boxes. Set the following:< first is the top edit box > (name)     = Tb_nametext = < blank > < second edit box > (name) = Tb_ Divisiontext = < blank > < third edit box > (name) = Tb_salarytext = < blank > < upper button > (name)   = Selectemployeebuttontext = employee < button > (Name)   = Closetext = close  next to create the event handler function for the button. The ' close ' button can simply call:         this. Close ();  to display the dialog box, let's create a command function in the class that instantiates the form as a modal dialog box. The following implementation code:      [Commandmethod ("Modalform")]      public void Showmodalform ()       {         modalform modalform = new Modalform ();         Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog (modalform);     }   Compile, load and run the Modalform command in AutoCAD to see if the dialog box works. Try resizing the dialog box in the lower-right corner of the dialog box, and then close it. Note that when you reuse the Modalform command, the dialog box appears where you left off last time! This is a feature of the ShowModalDialog method. The size and position values are saved by AutoCAD. The    ' Select Employee ' button will first perform a simple entity selection. This can be done by using the Editor.getentity () method, which is much more convenient to select a single entity than to use a selection set. Here's how to use the code for this method:            promptentityoptions prEnt = new Promptentityoptions ("Select an Employee");            Promptentityresult prentres = ed. GetEntity (prent),  16) adds the above code to the Selectemployeebutton_click handler function and joins the required database, command line, transaction settings variable, and a try catch block. Don't forget to destroy them in the finally block. Use Promptstatus.ok to test the return value of the getentity, call This.show and exit the handler function if the return is not equal. Once the return value we obtained is OK, we can use the Promptentityresult.objectid () method to get the object Id of the selected entity. This ID can be passed into the AsdkClass1 with a fixed string array.Listemployee function to obtain detailed information about the employee. The following code can be used to illustrate:         ArrayList saemployeelist = new ArrayList ();              Asdkclass1.listemployee ( Prentres.objectid, Saemployeelist);            if ( Saemployeelist.count = 4)             {                 tb_name.text = saemployeelist[0]. ToString ();                tb_ Salary.text = saemployeelist[1]. ToString ();                tb_ Division.text = saemployeelist[2]. ToString ();           } 17) to add the above code, It displays the employee details in the form's edit box.   Before we start testing the code, we need to remember that the code is running in a modal dialog box, which means that when the dialog box is visible, the userInteroperability with AutoCAD is prohibited. Before the user can select an Employee object, we must hide the form. When the selection is over, we can station the form again (for example, it can be in the function of the finally block) 18) before selecting the code that hides the form (for example, before a try block) ' this. Hide ' and the code that displays the form after the selection is finished (for example, can be in a finally block) ' this. Show '. Compile, load, and run the Modalform command in AutoCAD to see if the dialog box works. Try selecting an entity and populating the value of the edit box in the form.   Part fourth in the AutoCAD Options dialog box, add a page   The last part of this chapter will show you how to define a user control that can be displayed as a page in the AutoCAD Options dialog box. We can use this page to set the default values for the duration of the program run. In the employee example, we simply set the Sdivisiondefault and Sdivisionmanager strings in the AsdkClass1 class. 19 Add another user control named ' employeeoptions ' in the project. Add two edit boxes and label controls to the control, as shown in the following illustration:<!--[if!vml]--><!--[endif]-->  use the Properties window to set the properties of the edit box, set the following:< edit box > (Name )     = Tb_employeedivisiontext = < blank > < edit box below > (Name) = Tb_divisionmanagertext = < Blank >  using the. NET API to display a custom multi-page dialog box requires two steps. First, you know when the Options dialog box appears by passing in the address of the member function that you want to invoke. The second is to implement the callback function. The second argument passed into the callback function is an ' Tabbeddialogeventargs ' object that we must use to invoke the ' addtab ' function. AddTab uses a header string and an instance of a ' tabbeddialogextension ' object that encapsulates our form (in fact, the user control). In the Tabbeddialogextension constructor, we enter an instance of the form and the address of the callback function (OnOK, OnCancel, or onhelp). &NBSP;20) in the Employeeoptions class, add a name namedAddtabdialog public static function, which adds an event-handling:      public static void Addtabdialog () that can be invoked by the system.       {         Autodesk.AutoCAD.ApplicationServices.Application.DisplayingOptionDialog + = new Tabbeddialogeventhandler ( Tabhandler);      }  joins the code calling this function in the Initialize function of AsdkClass1. Because this function is invoked at the start of the program (because the class already implements the Iextensionapplication interface), the multi-page dialog box is automatically loaded. 20a implements an identical function to remove event processing, using the-= keyword of C #. Here, you can see that we have added a handler function for the Displayingoptiondialog event of the Application object in AutoCAD, and this function will call the ' Tabhandler ' function. So then we're going to implement this function. 21 Add the following code to implement the handler function:      private static void Tabhandler (object sender, Autodesk.AutoCAD.ApplicationServices.TabbedDialogEventArgs e)       {          employeeoptions employeeoptionspage = new Employeeoptions ();          e.addtab ("Acme Employee Options",             New Tabbeddialogextension (             Employeeoptionspage,             New Tabbeddialogaction (Employeeoptionspage.onok));     }  We first instantiate a Employeeoptions object. And then call E. AddTab (), a tabbeddialogextension instance is passed in this function. The Tabbeddialogextension constructor uses the Employeeoptionspage instance and a Tabbeddialogaction object. The Tabbeddialogaction object's arguments can be OK, Cancel, or help callback functions. In this function, we are using OK. 22 Now the rest is to determine the content of the callback function, which is the content of the OnOK. As we've said before, we just set the static members of the ASDKCLASS1, which is to set the values in the Tb_divisionmanager and tb_employeedivision edit boxes. The following is code:      public void OnOK ()       {          Asdkclass1.sdivisiondefault = tb_employeedivision.text;          Asdkclass1.sdivisionmanager = tb_divisionmanager.text;     }  compilation, Mount and select the AutoCAD Options menu item toTake a look at our custom dialog box. Try setting the value in the dialog box and instantiating an employee. You can use the Printoutemployee command to view detailed information.   Additional questions: How do I make the dialog box's edit box automatically appear as the contents of the manager and division strings in AsdkClass1?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.