Escolar Documentos
Profissional Documentos
Cultura Documentos
Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create Each Type Of Component
Introduction
C# is a modern programming language supported by an extensive set of API structures and classes. i.e., The .Net Framework C# supports event-driven programming normally associated with Microsoft Windows applications. One normally thinks of events as being generated by GUI components but any object can generate an event if its programmed to do so
Generally speaking, two logical components are required to implement the event processing model: 1) An event producer (or publisher) 2) An event consumer (or subscriber) Each logical components has assigned responsibilities Consider the following diagram
Object A
(Event Publisher)
Object B
(Event Subscriber) Event Handler Code
(Event Publisher)
Button
MainApp
(Event Subscriber) onButtonClick
The .Net API contains lots of classes that generate different types of events Most are GUI related Can you think of a few? It also contains lots of Delegates Can you name at least one? Lets take a closer look at the C# event processing model
To implement custom event processing in your programs you need to understand how to create the following component types: Delegates Event Generating Objects (publishers) Events Event Notification Methods Event Handling Objects (subscribers) Event Handler Methods
Required Components
To implement custom event processing in your programs you need to understand how to create the following component types:
Delegates Event Generating Objects (publishers) Events Event Notification Methods Event Handling Objects (subscribers) Event Handler Methods
Delegate
Delegate types represent references to methods
first one being of type Object and the second being of type EventArgs. Its return type is void. Any method, so long as its signature matches that expected by the delegate, can be handled by the delegate.
or MulticastDelegate class
Depends on whether one (Delegate) or more
MulticastDelegate
The C# compiler does it for you
each node of the list contains a pointer to a subscribers event handler method
A publisher is any class that can fire an event and send event notifications to interested subscribers A publisher class contains the following critical elements:
An event field
This
A subscriber is a class that registers its interest in a publishers events A subscriber class contains one or more event handler methods
An event is a field in a class Events are declared with the event keyword Events must be a delegate type
An event field will be null until the first subscriber subscribes to that event
In addition to an event field a publisher will have a method whose job is to start the subscriber notification process when the event occurs
An event notification method is just a normal method It usually has a parameter of EventArgs or a user-defined
subtype of EventArgs. But it can have any number and type of parameters as required.
MainApp.cs
using System; namespace CustomEventExample { public delegate void ElapsedMinuteEventHandler(Object sender, MinuteEventArgs e); } // end CustomEventExample namespace
using System; namespace CustomEventExample { public class MinuteEventArgs : EventArgs { private DateTime date_time; public MinuteEventArgs(DateTime date_time){ this.date_time = date_time; } public int Minute { get { return date_time.Minute; } } } }
using System; namespace CustomEventExample { public class Publisher { public event ElapsedMinuteEventHandler MinuteTick; public Publisher(){ Console.WriteLine("Publisher Created"); }
public void countMinutes(){ int current_minute = DateTime.Now.Minute; while(true){ if(current_minute != DateTime.Now.Minute){ Console.WriteLine("Publisher: {0}", DateTime.Now.Minute); onMinuteTick(new MinuteEventArgs(DateTime.Now)); current_minute = DateTime.Now.Minute; }//end if } // end while } // end countMinutes method
public void onMinuteTick(MinuteEventArgs e){ if(MinuteTick != null){ MinuteTick(this, e); } }// end onMinuteTick method } // end Publisher class definition } // end CustomEventExample namespace
using System; namespace CustomEventExample { public class Subscriber { private Publisher publisher; public Subscriber(Publisher publisher){ this.publisher = publisher; subscribeToPublisher(); Console.WriteLine("Subscriber Created"); } public void subscribeToPublisher(){ publisher.MinuteTick += new ElapsedMinuteEventHandler(minuteTickHandler); }
public void minuteTickHandler(Object sender, MinuteEventArgs e){ Console.WriteLine("Subscriber Handler Method: {0}", e.Minute);
} } // end Subscriber class definition } // end CustomEventExample namespace
public class MainApp { public static void Main(){ Console.WriteLine("Custom Events are Cool!"); Publisher p = new Publisher(); Subscriber s = new Subscriber(p); p.countMinutes(); } // end main } //end MainApp class definition } // end CustomEventExample namespace
OUTPUT
AGENDA
The Delegation Event model Event Listeners Event Classes Event Listener Interfaces Anonymous Inner Classes Examples
A source generates an event and sends it to one or more listeners. The listener simply waits until it receives an event. Once an event is received, the listener processes events and then returns. Listeners must register with a source in order to receive an event notification.
Events
o
An event is an object that describes a state change in a source. Events are generated by
Pressing a button Entering a character via the keyboard Selecting an item in a list Clicking the mouse
And so on..
Event Sources
o
General form
public void addTypeListener(TypeListener el) public void removeTypeListener(TypeListener el)
Event Listeners
o
A listener is an object that is notified when an event occurs. Two Requirements : It must have been registered with one or more sources to receive notifications. It must implement methods to receive and process these notifications.
EventObject
o o
The root of the java event class hierarchy is EventObject, which is in java.util. It is the super class of all the events. Two methods: getsource() - returns the source of the event. toString() - returns the string equivalent of the event.
o o
AWTEvent class
o o o
Defined within the java.awt package. Subclass of EventObject Superclass of all AWT-based events that are handled by the delegation event model.
Java.awt.event
Event class Action Event Description Generated when a button is pressed,a list item is double-clicked, or a menu item is selected.
AdjustmentEvent
ComponentEvent
ContainerEvent
Generated when a component is added to or removed from a container. Generated when a component gains or loses keyboard focus.
FocusEvent
Description Abstract superclass for all component input event classes. Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected. Generated when input is received from the keyboard.
KeyEvent
MouseEvent
Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component.
Generated when the mouse wheel is moved. Generated when the value of a text area or text field is changed. Generated when a window is activated,closed, deactivated, deiconified, iconified, opened or quit.
The ActionListener Interface void actionPerformed(ActionEvent ae) The AdjustmentListener Interface void adjustmentValueChanged(AdjustmentEvent ae) The ComponentListener Interface void componentResized(ComponentEvent ae) void componentMoved(ComponentEvent ae) void componentShown(ComponentEvent ae) void componentHidden(ComponentEvent ae)
The FocusListener Interface void focusGained(FocusEvent fe) void focusLost(FocusEvent fe) The ItemListener Interface void itemStateChanged(ItemEvent ie)
The KeyListener Interface void KeyPressed(KeyEvent ke) void KeyReleased(KeyEvent ke) void KeyTyped(KeyEvent ke)
The MouseListener Interface void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me) The MouseMotionListener Interface void mouseDragged(MouseEvent me) void mouseMoved(mouseEvent me) The MouseWheelListener Interface void mouseWheelMoved(MouseWheelEvent mwe)
public void mouseClicked(MouseEvent me) { mouseX=0; mouseY=10; msg = Mouse clicked; repaint(); } public void mouseEntered(MouseEvent me) { mouseX=0; mouseY=10; msg = Mouse Entered; repaint(); }
public void mouseDragged(MouseEvent me) { mouseX= me.getX(); mouseY=me.getY(); msg= * ; showStatus( Dragging mouse at + mouseX + mouseY +mouseY); repaint(); } public void paint(Graphics g) { g.drawString(msg,mouseX,mouseY); } }
C#:
static void Main(string[] args)
string is shorthand for the System.String class in C#. Another interesting point is that in C#, your Main method can actually be declared to be parameter -less
C#:
System.Console.WriteLine("Hello world!"); or Console.WriteLine("Hello again!");
C#:
To declare constants in C# the const keyword is used for compile time constants while the readonly keyword is used for runtime constants. The semantics of constant primitives and object references in C# is the same as in Java. const int K = 100;
IMPORTING LIBRARIES
Both the langugaes support this functionality and C# follows Javas technique for importing libraries: C#: using keyword
using System; using System.IO; using System.Reflection ;
Enumerations
Java's lack of enumerated types leads to the use of integers in situations that do not guarantee type safety. C# code:
p ub li c en um Di re ct io n { No rt h= 1, Ea st =2 , We st= 4, S ou th =8} ; Usage: D ir ec ti on wa ll = D ir ect io n. No rt h;
Reference
Websites: Java vs. C#: Code to Code Comparison http://www.javacamp.org/javavscsharp/ A Comparative Overview of C#: http://genamics.com/developer/csharp_comparativ e.htm
THANK YOU.