Autodesk Official latest. NET tutorial (vi) (vb.net edition)

Source: Internet
Author: User
Tags command line constructor finally block 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 (GetType (ASDKCLASS1)) >  public Class asdkclass1     Implements iextensionapplication  1)    now modifies 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.      Overridable Sub Initialize () Implements iextensionapplication.initialize    End sub     Overridable Sub Terminate () Implements iextensionapplication.terminate     End sub  in order to join a custom context menu, we must define a member 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 VB keyword ' AddHandler ' and ' AddressOf ' to determine which function to handle the event. Please familiarize yourself with this design pattern as soon as possible. NET will use a lot of. &NBSP;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. Sub Addcontextmenu ()         try             M_contextmenu = New contextmenuextension ()              m_contextmenu.title = "Acme Employee Menu"               Dim mi as menuitem            mi = New MenuItem ("Create Employee")             AddHandler mi. Click, AddressOf callbackonclick            m_ Contextmenu.menuiTEMs. ADD (MI)              Application.adddefaultcontextmenuextension (m_contextmenu)         Finally         End try    End sub     Sub Removecontextmenu ()         try             If not m_contextmenu are nothing then                 application.removedefaultcontextmenuextension (M_contextmenu)                  M_contextmenu = nothing             End if        finally        End try    End sub  Note we used the ' Callbackonclick ' function. We want this function (which we haven't defined yet) to respond to menu item selection events. In our exampleThe child we want to do is call our member function ' Create () '. Please add the following code.      Sub Callbackonclick (ByVal Sender as Object, ByVal e as System.EventArgs)          Create ()     end sub  Now, call the Addcontextmenu () function from Initialize (), and likewise, Please call Removecontextmenu () in Terminate (). 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. &NBSP;&NBSP;3)   Modify Callbackonclick to lock the document:    Sub Callbackonclick (ByVal Sender as Object, ByVal e As System.EventArgs)         Dim doclock as Documentlock = Application.DocumentManager.MdiActiveDocument.LockDocument ()         Create ()         doclock.dispose ()     End sub  Note that we have retained a ' Copy of Documentlock ' object. To unlock the document, we just need to destroy the docum.Entlock 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 look good in conjunction with AutoCAD and effectively reduces code duplication. 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. &NBSP;&NBSP;4)    adds a user control in Solution Explorer 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. &NBSP;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 ("Employee Palette") Dim myForm as Modelessform = new Modelessfor M () Ps. ADD ("Employee paletTE ", MyForm) PS. MinimumSize = New System.Drawing.Size (+) PS. Visible = true 6)   Add the above code to the CreatePalette () function. ' PS ' needs to be declared outside the function:  dim ps as Autodesk.AutoCAD.Windows.PaletteSet = Nothing adds 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 = 65  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 include the following members in the AsdkClass1 class:     public Shared sdivisiondefault as String = "Sales"      public Shared Sdivisionmanager as String = "Fiona Q. Farnsby" ' For this, your can chose any name to you Like&nbs p; 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. &NBSP;7) in order to support drag-and-drop, we first need an object to drag. Under the edit box, add a Label control named DraglabelPieces, set the text of the label as 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, you should note that the default Draglabel is declared as ' WithEvents ', which allows the Draglabel object to receive notification of events that affect it, including ' MouseMove ' that we are interested in. &NBSP;8)     Add the following function declaration to the Modelessform class:  private Sub draglabel_mousemove ()   is now in ' Handles Draglabel. ' Add dot to see smart tip:  private Sub _ Draglabel_mousemove () Handles draglabel.  can see all the events we can select. Find ' MouseMove ' and add it. Below the MouseMove event there is a line of blue (smart tip), because they are not the same in form. Typically, event handling uses two parameters, the sender of an object class, and the arguments associated with the event. For MouseMove, we have to do the same thing. Change the declaration of the function to receive ' sender ' and ' e '.      Private Sub draglabel_mousemove (ByVal sender as System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles draglabel.mousemove     End sub  runs this project, Check to see if the function is invoked when the mouse passes through the text. We can also further know whether the left mouse button is not pressed:  if (System.Windows.Forms.Control.MouseButtons = System.Windows.Forms.MouseButtons.Left) Then end if  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 simply create a class derived from this base class and implement theThe function you want. In our case, what we need is OnDrop (). &NBSP;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.  public Overrides Sub OnDrop (ByVal e as System.Windows.Forms.DragEventArgs) end sub  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. &NBSP;10)    Add the following code to the left mouse button (MouseButtons.Left) handler function:  application.dodragdrop (Me, ME, System.Windows.Forms.DragDropEffects.All, New Mydroptarget ())   Note that we passed ' me ' two times. The first time is for the control parameter and the second is for incoming user custom data. Because we're passing in an instance of the Modelessform class, we can use it to get the value of the edit box when we drop it. &NBSP;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. &NBSP;12)    Next, get the Modelessform object passed into the DragEventArgs parameter:  dim Ctrl as Modelessform = e.Data.GetData ( GetType (modelessform)   Please note how to use the GetType keyword to make the parameters strongThe system is transformed into an example of modelessform.    Use the above example to invoke ASDKCLASS1 Members:  asdkclass1.createdivision (Ctrl.tb_Division.Text, Asdkclass1.sdivisionmanager) Asdkclass1.createemployee (Ctrl.tb_Name.Text, Ctrl.tb_Division.Text, 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 ' Shared '. Because the public static method can only invoke other Shared methods, you need to modify the methods in several AsdkClass1 classes to ' shared '. Please make the relevant changes (there should be at least 4 items to be modified). &NBSP;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. &NBSP;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 &GT;&NBsp;< second edit box > (name) = Tb_divisiontext = < blank > < third edit box > (name) = Tb_salarytext = < Blank >  < top button > (name)   = Selectemployeebuttontext = Select employee < lower button > (name)   = Closetext = close  the event handler function that creates the button next. The ' close ' button can simply call:       me.close ()   To display the dialog box, let's create a command function in the class that takes the form as a modal dialog box. The following implementation code:       <commandmethod ("Modalform") > _      Public Sub showmodalform () Dim modalform as Modalform = New modalform () application.showmodaldialog (modalform) End Sub   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:  dim prent as Promptentityoptions = New promptentityoptions ("Select an Employee") Dim Prentres as Prom Ptentityresult = ed. GetEntity (prent) &NBSP;16)    adds the above code to the Selectemployeebutton_click processing 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.listemployee function with a fixed string array to get the employee's detailed information. You can use the following code to illustrate:             Dim saemployeelist ( -1) as String ' This is redimed in the Listemployee function.         & Nbsp;   asdkclass1.listemployee (Prentres.objectid, saemployeelist)              If (saemployeelist.length = 4) then                 tb_name.text = saemployeelist (0)                  Tb_salary.text = saemployeelist (1)                  Tb_division.text = saEmployeeList (2)              end if 17)    adds the above code, which displays the employee details in the form's edit box.   Before we start testing the code, we also need to remember that the code is running in a modal dialog box, which means that when the dialog box is visible, the user's interoperability with AutoCAD is forbidden. 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 a finally block)    add code that hides the form before selecting it (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. &NBSP;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 >  it takes two steps to display a custom multi-page dialog box using the. NET API. 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 public static function named Addtabdialog, which adds an event handler that can be invoked by the system:      Public Shared Sub addtabdialog ()         AddHandler Application.displayingoptiondialog, AddressOf tabhandler    end sub  Add the code that calls this function in the AsdkClass1 initialize function. 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. &NBSP;20A) implements an identical function to remove event processing, using VB's removehandler keyword. 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.    Add the following code to implement the handler function:   private Shared Sub Tabhandler (ByVal sender as Object, ByVal e as Autodesk.auto Cad. Applicationservices.tabbeddialogeventargs)Dim employeeoptionspage as Employeeoptions = New employeeoptions ()  e.addtab ("Acme Employee Options", _new Tabbeddialogextension (_employeeoptionspage, _new tabbeddialogaction (AddressOf Employeeoptionspage.onok))      End sub  We first instantiated 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. &NBSP;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. Here is the code:  public Sub OnOK () Asdkclass1.sdivisiondefault = Tb_EmployeeDivision.TextAsdkClass1.sDivisionManager = Tb_ Divisionmanager.textend sub  compile, load and select the AutoCAD Options menu item to see 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?

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.