In-depth introduction (II)

Source: Internet
Author: User
Ii. Origins of events

In the traditional object-oriented concept, there is no "event" concept. In traditional object-oriented concepts, only data (also called field, field, and member variable) and methods (member functions and functions) are supported ). If I remember correctly, the concept of event first appeared in Microsoft's COM technology, because VB is based on ActiveX (one of COM, so the concept of "Event" is widely promoted by VB and well-known and used by many programmers-I am one of them.

. Net Framework is actually a higher-level encapsulation of COM. before the Net Framework name comes out, it is called "com3"-naturally, the event support is retained.

Iii. significance of the event

The Theory of Evolution says: "A natural resource exists if it is reasonable ."

Microsoft said: "I am the boss and it is reasonable to exist !"

Regardless of whether Microsoft is playing a big game or engaging in hegemony, the existence of the event indeed brings a lot of convenience to program development. At the design level, it makes the program concise, clear, and easy to maintain in terms of logical thinking. At the technical level, it makes the hard-to-understand Windows message passing mechanism a brilliant package, greatly reducing the programmer's entry into the door.

From the perspective of software engineering, events are a notification mechanism and a way to maintain synchronization between classes.

Q: What synchronization?

Answer: Message synchronization!

Iv. Nature of events-encapsulation of message transmission

Events can be fired (fire, also known as "triggered"). Member events contained in a class can be fired in multiple situations. The most typical one is the Click Event of a button, which can be triggered by the user's mouse. It can also be stimulated by another software that tests the software through the Win32 API function.

Let's briefly discuss this click event:

In fact, if you understand the nature of Win32, you should understand that users cannot directly access a control. On the surface, the user clicked the button with the mouse. In fact, when you press the left mouse button, you send a "left-click [x, y] Point" message to the Windows operating system. Then, in windows, y] to allocate (route) the message to the control that should receive it-this is the message transfer/Routing Mechanism in windows.

Similarly, when you move the mouse, it seems that the pointer is moving as you wish, in fact, your mouse reports the current location to the Windows operating system at a frequency of several hundred times per second, then, in windows, I will show you a pretty pointer and draw it on the screen-Haha, we are all cheated!

However, these contents are invisible to C # programmers-they are encapsulated into "events ". Therefore, from the mechanism of the Windows system, the event mechanism is the packaging of the Windows message transmission mechanism.

The following code simulates the winform program automatically generated by Visual Studio 2005. After reading this information, you can write a winform and analyze the mechanism.

Code:

// ================= The true meaning of Water ====================== //
////
// Http://blog.csdn.net/FantasiaX //
////
// ========== Smooth migration, smooth migration //

Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Windows. forms; // Add a reference to the system. Windows. Forms and system. Drawing Assembly first!
Using system. drawing;

Namespace emulatewinform
{
// Custom emulateform class, derived from Form class.
Class emulateform: Form
{
// Two controls
Private button mybutton;
Private textbox mytextbox;

// Initialize each control and the form, and add the control to the controls array of the form.
Private void initializecomponent ()
{
Mybutton = new button ();
Mytextbox = new Textbox ();

Mybutton. Location = new system. Drawing. Point (195, 38 );
Mybutton. size = new system. Drawing. Size (75, 23 );
Mybutton. Text = "Click me ";
Mybutton. Click + = new eventhandler (mybutton_click); // hook event handler

Mytextbox. Location = new system. Drawing. Point (12, 12 );
Mytextbox. size = new system. Drawing. Size (258, 20 );

Controls. Add (mybutton );
Controls. Add (mytextbox );
TEXT = "emulateform ";
}

// Event handler provided by the emulateform class when the click event of mybutton occurs)
Void mybutton_click (Object sender, eventargs E)
{
Mytextbox. Text = "Hello, Event World! ";
}

// Execute the above Initialization Method in the constructor of the emulateform class
Public emulateform ()
{
Initializecomponent ();
}
}

Class Program
{
Static void main (string [] ARGs)
{
Emulateform myform = new emulateform ();
Application. Run (myform );
}
}
}
Code profiling:

1. to reference using system. drawing; using system. windows. forms; the two namespaces must be manually added to the system. drawing and system. windows. forms two assembly references.

2. The emulateform class is customized. Note that it is derived from the form class. For clarity, I have simplified the code to a very simple one ...... There are only two member variables. Mybutton is an instance of the button class, And mytextbox is an instance of the textbox class. The member method private void initializecomponent () of the emulateform class is completely an imitation of the real winform program. In its function body, the member variables are instantiated and initialized (such as determining the size and position), and added to the form's controls array. This function will be executed in the constructor of emulateform.

3. The most important part in this example is the initialization of mybutton. Note: mybutton. Click + = neweventhandler (mybutton_click );
Mybutton. Click Is the click event of mybutton. You may wonder: why don't you declare an event yourself? Haha, because the. NET Framework has prepared this event for us, you can simply use it. However, we want to explore the details, so I have to talk about this event carefully.

4. Detailed analysis of the button. Click Event: first, the event is based on the delegate, so which delegate is the mybutton. Click Event Based on? By searching for msdn, you can find that mybutton. Click inherits from the control class and is based on the eventhandler delegate. The following is the declaration of the eventhandler delegate.

[Serializableattribute]
[Comvisibleattribute (true)]
Public Delegate void eventhandler (Object sender, eventargs E)

If you do not know how the event is declared, go back and review "let's look at the event (I)".
In this statement, attribute is in square brackets and you do not need to ignore it for the moment. The key is to look at the eventhandler delegate: The parameter list of this delegate requires the function it is attached to (the event handler for the event) there should be two parameters: Object-type sender and eventargs-type E. What are the functions of these two parameters? Haha, actually, it's very interesting-as we have mentioned earlier, the event mechanism is encapsulation of the message mechanism. You can understand the message as a shell, and the sender is "Who fired shells ", E is "What is installed in the shell", and the target of the shell is of course the receiver of the message. Let's take a closer look at the fireeventargs class written in the previous article: Isn't there two member variables in this class? One is the floor that represents the fire floor, and the other is the firelevel that represents the fire level. With the firealarmring event of the building class instance, E of the fireeventargs class is sent to the instances of the employee and fireman classes. Then, the two instances open the "shells" and give corresponding processing based on the content of the launch. Just like the shells in a real war, such as regular shells, armor-piercing shells, and combustion shells, we have more than one "message shells", and we will like to share them with you:
Eventargs class: the one used in the click event. It's a normal bullet. Because clicking a button is a very simple event, it does not need to carry more information.
Mouseeventargs class: this class is initiated by the mousemove, mouseup, and mousedown events. Its instance carries a lot of other information, the most commonly used is an X and a Y-You can also think about it with your legs, that is the current location of the mouse. The demo is provided in the following example.
Painteventarg class: The painteventarg class is sent by the paint event. This shell is not simple, and the custom controls that are very beautiful cannot be left without it! There is a graphics in its belly, which represents a "canvas" that you can draw on "......
OK. First, let's list three of them in msdn, which are located in the derived classes tree of system. eventargs. Microsoft in. net Framework, from these event ARGs (event parameters), to various delegates, to a variety of events, has been well encapsulated for us, we just need to use it out.

5. Void mybutton_click (Object sender, eventargs E) is the emulateform class response function for the mybutton. Click Event (also called the event processor, eventhandler ). Check whether the parameter list is consistent with the eventhandler delegate.

6. There is nothing to say about the main program-the new emulateform instance will come out and use the application. Run method to execute the program.

7. By the way, here is a correction: The above has explained what the sender is -- it is the sender of the message. I have repeatedly found in some books such as "event senders". This is wrong! How can an event be "sent" only when it is triggered, triggered, or triggered? Not logical ......

Job1:

Create a winform program ,. Contains one panel, three Textbox, and one button.

Requirements:

1. When the mouse slides in the panel, textbox1 and textbox2 display the current X and Y respectively.

2. When you click the button, textbox3 will display Hello events world! .

Tip:

1. Pay attention to E of the mousemove event

2. Note that Visual Studio 2005 uses C #2.0, and uses the partial keyword to store the form1 class code in the form1.cs and form1.designer. CS files respectively.

Job2:

Upgrade the program in "deep dive event (I)" to the version of the event. (The Code will be provided later ).

 

Over

 

Legal disclaimer:This article is protected by intellectual property law. If any organization or individual needs to repost this article, it must ensure the integrity of the article (any omission or modification without the permission of the author shall be deemed as an infringement ). If you need to reprint the document, be sure to indicate the source of the articleCsdnTo protect the rights and interests of the website, please note that the author of the article isLiu tiemengAnd sends an email to the bladey@tom.com indicating the location and purpose of the article. Please repost this legal statement when reprinting. Thank you!

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.