Autodesk Official latest. NET Tutorial (vii) (vb.net edition)

Source: Internet
Author: User
Tags command line commit count integer modify connect variables reset
Tutorial Chapter 7th Events
This chapter discusses the events in AutoCAD. We will introduce the use of event handlers, especially the event handlers that monitor the AutoCAD commands and the event handlers that monitor objects modified by the AutoCAD command. Before explaining how to implement the event processing of AutoCAD, we will first briefly discuss. NET events.

The first part of VB. NET, events in
An event is only used to inform a behavior that has occurred. In Objectarx, we use a reactor (reactor) to handle AutoCAD events. In the AutoCAD. NET API, the OBJECTARX reactor was replaced with events.
Event-handling functions (or callback functions) are used to monitor and feedback events that occur in a program. Events can appear in different forms.
Before introducing the events in the AutoCAD. NET API, let's take a brief look at the broker.

Part 1a Agent
An agent is a class that stores method indexes (the concept is similar to a function pointer). The proxy pair method is type safe (similar to the function pointer in C). The agent has a specific form and return type. An agent can encapsulate any method that conforms to this particular form.
One use of an agent is as a distributor of the class that generates the event. The event is. NET environment, the first level object in the Although VB.net has hidden many of the details of event handling, events are always implemented by agents. Event proxies can be invoked multiple times (that is, they can store an index of more than 1 event-handling methods). They hold a list of registered event processing for the event. A typical agent has the following form:
Public Delegate Event (sender as Object, E as EventArgs)

The first parameter sender represents the object that raised the event. The second parameter, E, is a EventArgs parameter (or a derived class) that typically contains data for the event-handling function.

Part 1b AddHandler and RemoveHandler statements

To use the event handler, we have to associate it with the event. This is done by using the AddHandler statement. AddHandler and RemoveHandler allow you to connect, disconnect, or modify the handler functions associated with the event at run time.
When we use the AddHandler statement, we want to determine the name of the event initiator and use the AddressOf statement to determine the event handler function, for example:
AddHandler myclass1.anevent, AddressOf Ehandler

We said earlier that you want to use the RemoveHandler statement to disconnect the event from the event handler function (remove the contact). The syntax looks like this:
RemoveHandler Myclass1.anevent, AddressOf Ehandler

The 2nd part is dealt with. The AutoCAD events in net

In Objectarx, we use reactors to encapsulate AutoCAD events. In the AutoCAD. NET API, we can use events instead of OBJECTARX reactors.
Typically, the steps to handle an AutoCAD event are as follows:
1. Create an event handler function
When an event occurs, the event-handling function (or callback function) is called. Any action we want to take in response to the AutoCAD event is done in the event handler function.
For example, suppose we just want to notify the user that an AutoCAD object has been added. We can use the AutoCAD database event "objectappended" to complete. We can write callback functions (event handler functions) as follows:
Sub objappended (ByVal o as Object, ByVal e as Objecteventargs)
MessageBox.Show ("objectappended!")
' Add some code here
End Sub

The first parameter in the function represents the AutoCAD database. The second parameter represents the Objecteventargs class, which may contain data that is useful for processing functions.
2. Link the event handler function to the event
In order to begin the monitoring action, we must associate the event handler function with the event. Here, when an object is joined to the database, the Objectappended event occurs. However, the event handler function does not respond to this event unless we associate it with this event, for example:
Dim DB as Database
db = Hostapplicationservices.workingdatabase ()
AddHandler db. objectappended, New Objecteventhandler (AddressOf objappended)


3. Disconnect the event handler function
To terminate the monitoring of an action, we must disconnect the event handler function from the event. When the object is joined, we want to stop notifying the user of this event, and we want to disconnect the event handler function from the event objectappended.
RemoveHandler db. objectappended, AddressOf objappended

The 3rd part uses the event handler function to control the behavior of AutoCAD
The purpose of this chapter is to explain how AutoCAD events can be used to control behavior in AutoCAD graphics. Now, let's use the contents of the previous chapter (chapter sixth) to create several employee block indices in the AutoCAD graphic. We don't want the user to be able to change the position of the employee block index, and there is no such limit for the location of other non-employee block indexes. We'll do this with a mixture of database and document events.
First, we want to monitor the AutoCAD command that will be executed (using the Commandwillstart event). In particular, we want to monitor the move command. In addition, when an object is to be modified, we should be notified (using the Objectopenedformodify event) so that we can determine whether it is an employee block index. If you modify the object at this point, it may be invalid, because our modifications may trigger the event again, causing an unstable behavior. So we have to wait for the execution of the move command to end (using the Commandended event), and then we can safely modify the object. Of course, any modification to the block index will trigger the Objectopenedformodify event. We also need to set some global variables to indicate that a move command in the running and modified object is an employee block index.
Note: Because this chapter requires more code to get the desired results, we do not interpret any code that is not related to event handling, but simply paste them into the event handler. The focus here is on the successful creation and registration of event handler functions.
First step: Create New Project
We begin with the works of chapter sixth. Please add a new class AsdkClass2. We also want to add four global variables. The first two are boolean: one to indicate whether the command we are monitoring is active, and the other to indicate whether the Objectopenedformodify event handler function should be ignored.
' Global variables
Dim Beditcommand as Boolean
Dim bdorepositioning as Boolean


Next, we declare a global variable to represent a objectidcollection that stores the objectid of the object we choose to modify.
Dim changedobjects as New objectidcollection ()

Finally, we declare a global variable to represent a point3dcollection, which is used to contain the position of our selected object (three-dimensional point).
Dim employeepositions as New point3dcollection ()
Step 2nd: Create the first document event handler function (callback function)
Now we're going to create an event handler function. It will notify us when the AutoCAD command begins to execute. We want to check whether the value of Globalcommandname is move.
If e.globalcommandname = "Move" Then
' Set the ' global variables


' Delete all stored information


End If
If the move command starts, we'll set the value of the Boolean variable Beditcommand accordingly so that we know that the command we're monitoring is active. Similarly, we should set the other Boolean variable bdorepositioning to False to ignore the Objectopenedformodify event handler function. After two variables are set, we have to get the information for the selected block index during the command activity.
We should also empty the contents of the two collection objects. We only care about the currently selected object.
Step 3rd: Create a Database event handler function (callback function)
The database event handler function is invoked whenever an object is opened and is being modified. Of course, if the command we are monitoring is not active, we should skip any content that is invoked by this callback function.
If Beditcommand = False Then
Return
End If
Similarly, if the command we are monitoring has ended, and the Objectopenedformodify event is triggered again by another callback function, and when an object is modified, we want to block all actions performed by this callback function.
If bdorepositioning = True Then
Return
End If
The code for the remainder of this callback function verifies that we are processing an employee block index. If so, we get the Objectid and position (three-dimensional point). The following code can be pasted into this event handler function.

Public Sub objopenedformod (ByVal o as Object, ByVal e as Objecteventargs)
If Beditcommand = False Then
Return
End If

If bdorepositioning = True Then
Return
End If

Dim ObjID as ObjectId
ObjID = E.dbobject.objectid

Dim Trans as Transaction
Dim BT as Blocktable
Dim DB as Database
db = Hostapplicationservices.workingdatabase

trans = db. Transactionmanager.starttransaction ()
Try
' Use it to ' open the current object!
Dim ent as Entity = trans. GetObject (ObjID, Openmode.forread, False)
If TypeOf ent is blockreference Then ' We use. NET ' s RTTI to establish type.
Dim br as Blockreference = CType (ent, blockreference)
' Test Whether it is a employee block
' Open its extension dictionary
If Br. Extensiondictionary (). IsValid Then
Dim brextdict as Dbdictionary = trans. GetObject (Br. Extensiondictionary (), Openmode.forread)
If brextdict.getat ("EmployeeData"). IsValid Then
' Successfully got ' employeedata ' so br be employee block ref

' Store the ObjectID and the position
Changedobjects.add (ObjID)
Employeepositions.add (Br. Position)
' Get the attribute references,if any
Dim Atts as AttributeCollection
Atts = Br. AttributeCollection
If Atts. Count > 0 Then
Dim Attid as ObjectId
For each attid in Atts
Dim att as Attributereference
att = trans. GetObject (Attid, Openmode.forread, False)
Changedobjects.add (Attid)
Employeepositions.add (Att. Position)

Next
End If
End If
End If
End If
Trans.commit ()
Finally
Trans. Dispose ()
End Try
End Sub
Step 4th Create a second document event handler function (callback function)
When a command ends, the third event handler is invoked. Again, we check the global variable to verify that the command to be closed is the one we're monitoring. If that's what we're monitoring, then we're going to reset the variable:
If Beditcommand = False Then
Return
End If

Beditcommand = False

The action performed by this callback function will trigger the Objectopenedformodify event again. We have to be sure that all the actions associated with this event are skipped in this callback function.
' Set flag to skip openedformodify handler function
bdorepositioning = True


The remaining code for this callback function is used to compare the current (modified) position of the employee block index with its associated attribute reference to their initial position. If the position changes, we reset the initial position in this callback function. The following code can be pasted into this event handler function.

Public Sub cmdended (ByVal o as Object, ByVal e as CommandEventArgs)
' is our monitored command active?
If Beditcommand = False Then
Return
End If

Beditcommand = False

' Set flag to bypass Objectopenedformodify handler
bdorepositioning = True

Dim db as Database = Hostapplicationservices.workingdatabase
Dim Trans as Transaction
Dim BT as Blocktable
Dim Oldpos as Point3D
Dim Newpos as Point3D
Dim I as Integer
Dim J as Integer = 1
For i = 0 to Changedobjects.count-1
trans = db. Transactionmanager.starttransaction ()
Try
BT = trans. GetObject (db. Blocktableid, Openmode.forread)
Dim ent as Entity = CType (trans. GetObject (Changedobjects.item (i), openmode.forwrite), Entity)
If TypeOf ent is blockreference Then ' We use. NET ' s RTTI to establish type.
Dim br as Blockreference = CType (ent, blockreference)
Newpos = Br. Position
Oldpos = Employeepositions.item (i)

' Reset blockref position
If not oldpos. Equals (Newpos) Then
Trans. GetObject (Br. ObjectId, Openmode.forwrite)
Br. Position = Oldpos
End If
ElseIf TypeOf ent is attributereference Then
Dim att as attributereference = CType (ent, attributereference)
Newpos = att. Position
Oldpos = Employeepositions.item (i)

' Reset attref position
If not oldpos. Equals (Newpos) Then
Trans. GetObject (Att. ObjectId, Openmode.forwrite)
Att. Position = Oldpos
End If
End If
Bt. Dispose ()
Trans.commit ()
Finally
Trans. Dispose ()
End Try
Next
End Sub

Step 5th Create a command to register/disconnect event handler functions
Create a addevents command, using the + = statement to connect the 3 event handlers above to their respective events. In this command, we should also set the global Boolean variable:
Beditcommand = False
bdorepositioning = False

Create another command removeevents, using the RemoveHandler statement to disconnect the event handler function from the event.
6th Step: Test Engineering
To test this project, create one or more employee block indexes using the Create command. If you want to make a comparison, you can also insert some non employee block index.
Type the addevents command at the command line to execute it.
Enter the move command at the command line, and then select the block index you want. Note that when the move command ends, the employee block index (including attributes) remains in place.
Execute the removeevents command, and then try the move command. Note that the Employee block index can now be moved.

Additional question: Add an additional callback function that is triggered when the user changes the "Name" attribute of the employee block index.

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.