Custom Event generation in C #

Source: Internet
Author: User

About Custom Event generation in C:

Objectives:Use an instance to describe how to create, trigger, receive, and cancel events in C. The example is a form.Program, A button and a tag. When you click the button, an event is triggered to get the current time. If the second is the last 30 seconds, a wasn' t a right time is output !!

1. Create an event type:

1. Create a form application and add a button and lebelinfo. The names are buttonraise and labelinfo respectively.

2. Define a delegate:
Add in the Declaration section of the Form class,
Public Delegate void actioneventhandler (Object sender, actioncanceleventargs E );
Here we declare a new delegate type actioneventhandler, because we need to customize the eventarg class later (the above can be seen as the actioncanceleventargs class), and the method name must match the delegate.

3. Define an event:
AboveCodeAdd,
Public static event actioneventhandler action;
We define an event called action. the syntax of the event definition requires that the event-related delegation be specified.

4. Create your own eventarg class:
Define a class code in the program as follows:
Namespace windowsapplication1
{
Public class actioncanceleventargs: system. componentmodel. canceleventargs
{
String message = string. empty;

Public actioncanceleventargs (): Base (){}

Public actioncanceleventargs (bool cancel): Base (cancel ){}

Public actioncanceleventargs (bool cancel, string message)
: Base (cancel)
{
This. Message = message;
}

Public String message
{
Get {return message ;}
Set {message = value ;}
}
}
}
This new actioncanceleventargs class is actually derived from canceleventargs, while canceleventargs is derived from eventargs. Canceleventargs adds the cancel attribute, which is a bool type and notifies the sender object that the receiver wants to cancel or stop event processing. We add a message attribute for actioncanceleventargs, which contains a string that passes an event processing status during event processing.
All eventargs-based classes are responsible for transmitting event information back and forth between the transmitter and receiver. In most cases, the information used in the eventargs class is used by the receiver object (the later actioncanceleventargs eV) in the event processing program. However, sometimes the event handler can add information to the eventarg class so that it can be used by the sender. This is what we do here (the receiver transmits the information to the Message attribute in the sender Based on the status ).

Ii. Events:

1. Activate the Action event through one action (click the button buttonraise ):
Add a click event handler for the buttonraise button first:
Private void buttonraise_click (Object sender, eventargs E)

2. Call the event with the correct parameter in the handler: Add the following code,
Actioncanceleventargs cancelevent = new actioncanceleventargs ();
Onaction (this, cancelevent );

It is to first create a new event data type actioncanceleventargs, and then pass it as a parameter to the handler of the previously defined action event (the event is triggered through action (this, cancelevent, but we call it through onaction ). Here, our action event is equivalent to ours. the move and click events in. NET are the same, but they are still empty. If this event is triggered, an empty reference exception will occur, therefore, if we define action events as the base events in other classes, we need to define relevant event handlers as long as an action is triggered.

3. We define a function called onaction to trigger an event. (In addition, on is the naming convention)
Protected void onaction (Object sender, actioncanceleventargs E)
{
If (action! = NULL) // capture null reference errors
Action (sender, e );
}
If you derive a new class that contains the method and event, you must override the onaction method and call base. onaction () in the rewrite code to raise this event.

 

3. accept and handle the event:
1. A new busentity class is defined below:
Namespace windowsapplication1
{
Public class busentity
{
String time = string. empty;

Public busentity ()
{
Form1.action + = new form1.actioneventhandler (form1_action );
}

Private void form1_action (Object sender, actioncanceleventargs E)
{
E. Cancel =! Doactions ();
If (E. Cancel)
E. Message = "wasn' t the right time .";
}

Private bool doactions ()
{
Bool retval = false;
Datetime TM = datetime. now;

If (TM. Second <30)
{
Time = "the time is" + datetime. Now. tolongtimestring ();
Retval = true;
}
Else
Time = "";

Return retval;
}

Public String timestring
{
Get {return time ;}
}
}
}
Key code:
1. the constructor declares the handler for the form1.action event (register the event ):
Form1.action + = new form1.actioneventhandler (form1_action );
Note that the action event defined in form1 is registered here, which is not defined elsewhere.

2. The action event handler (triggered by onaction () in the form1 class ):
Private void form1_action (Object sender, actioncanceleventargs E)
The processing is done by calling the doaction function. It returns a bool value and assigns the status information to the Message Member of the actioncanceleventargs parameter of the event data type.

3. Complete the form1 program:
(1) create a private busentity member in the class.
(2) initialize it in the constructor: busentity = new busentity ();
(3) Complete Event processing by clicking the button, and trigger and Process Action events:
private void buttonraise_click (Object sender, eventargs E)
{< br> actioncanceleventargs cancelevent = new actioncanceleventargs ();
onaction (this, cancelevent);
If (cancelevent. cancel)
labelinfo. TEXT = cancelevent. message;
else
labelinf O. Text = busentity. timestring;
}< br> Note: The actioncanceleventargs object is created, the Action event is triggered, and the newly created actioncanceleventargs object cancelevent is passed. When the onaction method is called to trigger an event, the code of the Action event processing program in the busentity object is executed. If other objects have registered events, they will also execute. Remember: if other objects process event actions, they will also see the same actioncanceleventargs object. If you need to determine which object has canceled the event, and if multiple objects have canceled the event, you must include a list-based data structure in the actioncanceleventargs class.

4. Cancellation event:
After the handler registered with the delegate is executed, You can query the actioncanceleventargs object and determine whether it is canceled. That is, the following code:
If (cancelevent. Cancel)
Labelinfo. Text = cancelevent. message;
Else
Labelinfo. Text = busentity. timestring;

Summary:Above is my personal pass professional C #2005. net 3.0, which summarizes how to use eventargs-based objects in events and events to transmit information in applications. The program example is from this tutorial.

Copyright 2009 lcswr1987.ccbb. All rights reserved.

Post please indicate the source: http://hi.baidu.com/lcswr/blog/item/9ba59063c08890670d33fa05.html

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.