Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
Event etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Event etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

24 Haziran 2013 Pazartesi

jQuery events and parameters

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$("button").click(function(){
  $("#ddiv").trigger("eventAdi", 
                     [
                       { Adi: 'Abdulcabbar', Soyadi :'Kuddüs', 
                         Dersleri:['cebir','türkçe','müzik']}, 
                       12, 
                       'bir tane daha'
                     ]
                    );
});

$(document).ready(function () {
  $("#ddiv").on('eventAdi', 
                { 
                  mesaj:"Tetiklediğiniz olay mesajı",
                  eventOncesi:function(){},
                  eventSonrasi:function(){},
                }, 
                calisacakFonksiyon);
});

function calisacakFonksiyon(e, a, b, c) {
  console.log(e);
  console.log(a);
  console.log(b);
  console.log(c);
  console.log("----------------------");
  console.log(arguments);
}

</script>
<meta charset=utf-8 />
</head>
<body>
  <div id="ddiv">aaa</div>
  <button>düğmee</button>
</body>
</html>

25 Nisan 2013 Perşembe

jQuery üzerinden observer pattern oluşturulması

$ içinde tanımlı olan ve jQuery nesnelerine sarılan on, off, trigger metotları vardır. trigger Metodu bir tetikleyicidir ve hangi olayın tetiklenmesini istiyorsak, ilgili değişkenleri ikinci parametrede vererek çalıştırırız.


on Metodu bir olayın tetiklenmesi halinde çalışır. Birinci parametre hangi event durumunda çalışacağını, ikinci parametre ise hangi fonksiyonun çalışacağını gösterir.


off Metodu ise daha önce bir olaya eklenmiş bir metodun kaldırılması esasına dayanır.


Yukarıdaki bu metotların çalışabilmesi için önce hangi nesneye kilitlediğinizi seçmelisiniz ve bu nesne tabii ki jQuery örneği olmalı. Mesela her div'e tıklandığında zapa zupa olsun: $('div').on('click',zapaZupaFonksiyonunuCagir());
Eğer bir tıklama olmadan programatik olarak çağırmak isterseniz $('div').trigger('click',['extra parametreler']); ile çağırabilirsiniz olayları.

Şimdi biliyoruzki jQuery nesneleri on,off,trigger metotlarına sahiplerken $ buna sahip değil. Bunu sağlamak için bir jQuery nesnesi yaratalım:
var o = $({});
Bu nesneden o.trigger() diyerek metot çağırmakla o['trigger']() diyerek metot çağırmak arasında bir fark yoktur. Neticede javascript nesnesinin bir özelliğini çağırıyoruz ve fonksiyonlarda bu nesnelerin bir propertysi gibidirler.


Peki 'on' metodunun içeriği zaten jQuery içinde tanımlanmış ve sadece nesnelere bağlanabiliyorsa biz jQuery örneğimiz için on fonksiyonunun adını değiştirebilir miyiz?
o['hebeleOlsun'] = function(){ o.on.apply(o, arguments); }; burası azıcık karışık gelebilir. Baş taraf çok basit. hebeleOlsun diye bir özellik ekliyoruz "o" nesnemize. Bu nesneye anonymous bir function atıyoruz. Bu durumda o['hebeleOlsun']() ya da o.hebeleOlsun() çağrıları bu anonymous fonksiyona çağrı yapacak ve tüm parametrelerde bu metot içinde arguments dendiğinde elde edilebilecek. Şimdi sırada apply var. apply da bir metot çağrısı ama kime yapılıyor? Bir başka metotan yapılabiliyor ki burada bizim "on" metodumuzun üstünden yapıldığını farketmişsinizdir. Peki parametrelerin anlamı ne? Birinci parametre bu fonksiyon içinde this diyerek elde edebileceğimiz değişken olacak. Ki; biz burada o nesnesini gönderdik. Böylece apply ile çağırdığımız on fonksiyonu içinde artık this = o olmuştur. ON fonksiyonunun içine diğer diğer parametreleride arguments ile gönderiyoruz.

Peki biz jQuery içinden özelleştirilmiş bir olay oluşturma, bu olaya abone olma ve aboneliği silmek konusununu nasıl yazabiliriz:
<script>
        var o = $({});

        jQuery['yayinYap'] = function () {
            o.trigger.apply(o, arguments);
        };

        jQuery['uyeOl'] = function () {
            o['on'].apply(o, arguments);
        };

        jQuery['uyeOlma'] = function () {
            o['off'].apply(o, arguments);
        };

        $.yayinYap('onBasimKasindi',['bu bir event parametresi','bu da digeri',2,3,{oz:'el',li:'ck'}]);

        $.uyeOl('onBasimKasindi',function(e){ console.log('Başı kaşınan birisi var'); console.log(e); $.uyeOlma('onBasimKasindi','**'); });

Bunun pratik halleride var ama bu şeklini anladığınızda diğerleri daha anlamlı gelecektir.

Geç oldu, ben gider...

25 Mayıs 2010 Salı

ASP.NET Custom Control Event Handler





16 Mayıs 2010 Pazar

AS 3.0 - KeyboardEvent ve KeyCombinations

Hikaye şu: Sahnede bir mc var içinde resim, W tuşuna bastınmı yukarı kaysın, Shift + W tuşuna bastın mı daha hızlı kaysın. Kod şu:


import flash.events.KeyboardEvent;

// W tuşuna basıldığında resmi ileri götürelim.
stage.addEventListener(KeyboardEvent.KEY_UP,f_ileri);

function f_ileri(e:KeyboardEvent):void
{
//W tuşunun kodu ne?
if (e.keyCode == 87)
{
mcArkaPlan.y -= 10;
}
// Shift+w tuşunda iki katı hız yapsın.
if (e.shiftKey && e.keyCode == 87)
{
mcArkaPlan.y -= 20;
}
trace("Tuş: "+e.keyCode+" , Shifte basildi mi? = "+ e.shiftKey);
}


Videosu:


Kodu biraz ötele. Oyun konsoluymuş gibi W tuşuna basılı tutuyorsa kullanıcı, sürekli basıldığını kontrol etmeli. Bunu da ENTER_FRAME olayı ile yap. W ye basılıysa 10 hızında arka planı kaydır, Shift+W ise 20 hızında, tuşa basmaktan vazgeçtiyse kaydırmayı durdur. İşte kod:

import flash.events.KeyboardEvent;
import flash.events.Event;

var hiz:Number;
// Sahnedeki her frame geçişinde kontrol edelim hızımız ne?
// hiz==0 ise mcArkaPlan kaymamalı.Durmalı.
// Shift tuşu olmaksızın gidiyorsak yavaş, shift tuşuyla hızlı gitmeliyiz
stage.addEventListener(Event.ENTER_FRAME,f_SonDurum);
function f_SonDurum(e:Event):void
{
if (hiz != 0)
{
mcArkaPlan.y += hiz;
}
}

stage.addEventListener(KeyboardEvent.KEY_DOWN,f_ileri);
stage.addEventListener(KeyboardEvent.KEY_UP,f_dur);

function f_ileri(e:KeyboardEvent):void
{
// W tuşuna basıldığında resmi ileri götürelim.
if (e.keyCode == 87)
{
hiz = -10;
}
// Shift+w tuşunda iki katı hız yapsın.
if (e.shiftKey && e.keyCode == 87)
{
hiz = -20;
}
trace("Tuş: "+e.keyCode+" , Shifte basildi mi? = "+ e.shiftKey);
}

function f_dur(e:KeyboardEvent):void
{
hiz = 0;
}


AS 3.0 - MOUSE.OVER Olayı

Bir mc oluştur, ve ilk framine stop yaz ki sahneye koyduğunda çalışmasın. Çalışması işini mouse eventlerinden over ile yapacaksın.

Bir fonksiyon yaz ki mouse.over eventi ile tetiklensin. Aşağıdaki kod parçasını sahnede actions diye açtığın katmana(kodu ayrı kata koymak gelenektir) ilk frame e yaz. Bitti işte.

import flash.events.MouseEvent;
import flash.events.Event;

mcDaire.addEventListener(MouseEvent.MOUSE_OVER,f_Oyna);
function f_Oyna(e:Event):void
{
e.currentTarget.play();
}




5 Mart 2010 Cuma

Java ve Event Handling

Kaynaklar:
http://www.devshed.com/c/a/Java/Event-Handling-In-Java/
http://scatteredcode.wordpress.com/2011/11/24/from-c-to-java-events/

In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.


You are leaving for work in the morning and someone rings the doorbell….

That is an event!

In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events. When the user interacts with a program let us say by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. This code determines how to handle the event so the user gets the appropriate response.

In today’s tutorial we are going to learn event-driven programming, the event model of Java, and the different ways in which you can handle events.

Now lets taste our first cup of Java…

Components of an Event: Can be put under the following categories.

1. Event Object: When the user interacts with the application by clicking a mouse button or pressing a key an event is generated. The Operating System traps this event and the data associated with it. For example, info about time at which the event occurred, the event types (like keypress or mouse click). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects, which describe the events themselves. And Java has a number of classes that describe and handle different categories of events.

2. Event Source: An event source is the object that generated the event. Example if you click a button an ActionEvent Object is generated. The object of the ActionEvent class contains information about the event.

3. Event-Handler: Is a method that understands the event and processes it. The event-handler method takes the Event object as a parameter. Java uses Event-Delegation Model :with JDK1.1 onwards; you can specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is discarded. The four main components based on this model are Event classes, Event Listeners, Explicit event handling and Adapters. Let us take a closer look at them one by one.

Event Classes: The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. While most of the other event classes are present in java.awt.event package. The getSource() method of the EventObject class returns the object that initiated the event. The getId () method returns the nature of the event. For example, if a mouse event occurs, you can find out whether the event was click, a press, a move or release from the event object. AWT provides two conceptual types of events: Semantic and low-level events.

Semantic events are defined at a higher-level to encapsulate the semantics of user interface component’s model. Now let us see what are the various semantic event classes and what they generate:

• An ActionEvent object is generated when a component is activated

• An AdjustmentEvent Object is generated when scrollbars and other adjustment elements are used.

• A TextEvent object is generated when text of a component is modified.

• An ItemEvent is generated when an item from a list, a choice or checkbox is selected.

Low-Level Events is one that represents a low-level input or windows-system occurrence on a visual component on the screen. The various low-level event classes and what they generate are as follows:

• A ContainerEvent Object is generated when component are added or removed from container.

• A ComponentEvent object is generated when a component is resized, moved etc.

• A FocusEvent object is generated when component receives focus for input.

• A KeyEvent object is generated when key on keyboard is pressed, released etc.

• A WindowEvent object is generated when a window activity, like maximizing or close occurs.

• A MouseEvent object is generated when a mouse is used.

• A PaintEvent object is generated when component is painted.

Event Listeners: An object delegates the task of handling an event to an event listener. When an event occurs, an event object of the appropriate type (as illustrated below) is created. This object is passed to a Listener. A listener must implement the interface that has the method for event handling. A component can have multiple listeners, and a listener can be removed using removeActionListener () method. Next question in your mind must be what is an interface?. An Interface contains constant values and method declaration. The difference between classes and interface is that the methods in an interface are only declared and not implemented, that is, the methods do not have a body. What is the Need for interface? Are interfaces are used to define behavior protocols (standard behavior) that can be implemented by any class anywhere in the class hierarchy. The java.awt.event package contains definitions of all event classes and listener interface. The semantic listener interfaces define by AWT for the above mentioned semantic events are:

• ActionListener

• AjdustmentListener

• ItemListener

• TextListener

The low-level event listeners are as follows:

• ComponentListener

• ContainerListener

• FocusListener

• KeyListener

• MouseListener

• MouseMotionListener

• WindowsListener.



ActionEvent using the ActionListener interface: The following illustrates the usage of ActionEvent and ActionListener interface in a Classic Java Application (Example I).

//Save the file with MyEvent.java file and compile it using javac, 
//once complied errors free execute it.
Import javax.swings.*;
Import java.awt.event.*;
Public class MyEvent extends JFrame
{
JButton b1;
// Main Method
Public static void main (String arg[])
{
MyEvent event = new MyEvent();
}
//Constructor for the event derived class
Public MyEvent()
{
Super(“Window Title: Event Handling”);
b1 = new Jbutton(“Click Me”);
//place the button object on the window
getContentPane().add(“center”,b1);
//Register the listener for the button
ButtonListener listen = new ButtonListener();
b1.addActionListener(listen);
//display the window in a specific size
setVisible(true);
setSize(200,200);
}
//The Listener Class
Class ButtonListener implements ActionListener
{
//Definition for ActionPerformed() method
Public void ActionPerformed(ActionEvent evt)
{
JButton source = (JButton)evt.getSource();
Source.setText(“Button Has Been Clicked, Guru!”);
}
}
}
How does the above Application work?


• The execution begins with the main method.

• An Object of the MyEvent class is created in the main method.

• Constructor of the MyEvent class is invoked.

• Super () method calls the constructor of the base class and sets the title of the window as given.

• A button object is created and placed at the center of the window.

• A Listener Object is created.

• The addActionListener() method registers the listener object for the button.

• SetVisible () method displays the window.

• The Application waits for the user to interact with it.

• When the user clicks on the button labeled “Click Me”: The “ActionEvent” event is generated. Then the ActionEvent object is created and delegated to the registered listener object for processing. The Listener object contains the actionPerformed() method which processes the ActionEvent In the actionPerformed() method, the reference to the event source is retrieved using getSource() method. The label of the button is changed to “Button has been clicked, Guru!” using setText() method.

Tools of the Trade: Since the ButtonListener class has been declared under MyEvent class. Therefore ButtonListener class is an inner class.

For those of you folks who are more into using Java Applets here is easy sample which works.Type in the following code (Example 2) and save it as ButtonEvent.java and the compile using javac and view it using appletviewer. A short cut to avoid compiling a java file and html file separately you can enclose the applet tag normally containing applet code, height, width, param tags etc. within /* and */. Then compile as one single file, because the HTML tag will be read as html automatically. And when compiled error free run using Appletviewer tag.

/*
<Applet code = "ButtonEvent.class" height = 400 width = 400>
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.Applet;
Public class ButtonEvent extends Applet implements ActionListener 
{
Private Button b;
Public void init() {
b = new Button("Click me");
b.addActionListener(this);
add (b);
}
Public void actionPerformed (ActionEvent e) {
// If the target of the event was our Button
// In this example, the check is not 
// Truly necessary as we only listen to
// A single button
If (e.getSource () == b) {
getGraphics().drawString("OUCH Buddy",20,20);
}
}
}
The above sample code pretty much does the same thing
as Example I only the applet starts with the init() method first the button is added using the add() method and is registered with ActionListener(). Once the user clicks it, The event is trapped using the getSource() and delegated to the appropriate listener. The getGraphics() method of the image class is used along with drawString() method to draw the text given by the specified string.

Mouse Events, MouseListener and MouseMotionListener:

These are generated when a mouse is moved, clicked, pressed and released etc. The MouseEvent class represents these events as six constant values and has methods to get the co-ordinates at which a mouse event occurred. The mouse move and mouse drag are treated differently from the rest four mouse pressed, mouse released, mouse entered and mouse exited. Hence there are two types of mouse event listeners- MouseListener and MouseMotionListener.

The following code illustrates the usage of mouse event listeners. Watch out for messages on the status line of applet as and when the user performs a mouse event. (Example 3 also shows the co-ordinates at which the event occurred.

// Example 3: MouseEvents & MouseListener
/*
<Applet code = "mouseEvent.class" height= 400 width = 400 >
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class mouseEvent extends JApplet implements MouseListener, MouseMotionListener
{
Public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Public void mouseClicked(MouseEvent e)
{
showStatus("Mouse has been clicked at " + e.getX()+ "," + e.getY());
}
Public void mouseEntered(MouseEvent e)
{
showStatus("Mouse has been Entered at " + e.getX()+ "," + e.getY());
// For loop:to make sure mouse entered is on status bar for a few sec
For (int i= 0; i<1000000; i++);
} 
Public void mouseExited (MouseEvent e)
{
showStatus ("Mouse has been Exited at " + e.getX()+ "," + e.getY());
}
Public void mousePressed(MouseEvent e)
{
showStatus ("Mouse pressed at " + e.getX()+ "," + e.getY());
}
Public void mouseReleased(MouseEvent e)
{
showStatus("Mouse released at " + e.getX()+ "," + e.getY());
}
Public void mouseDragged(MouseEvent e)
{
showStatus("Mouse dragged at " + e.getX()+ "," + e.getY());
}
Public void mouseMoved(MouseEvent e)
{
showStatus("Mouse moved at " + e.getX()+ "," + e.getY());
}
}
Since the applet implements MouseListener and
MouseMotionListener it has to provide for the functionality of all their methods. Observe the mouseEntered() method has a small loop to ensure the mouse entered message remains on the status bar for a while. {mospagebreak title=Key Frienldy Codes} Keyboard Events and KeyListener: They are generated on pressing or releasing a key. The KeyEvent class contains constants to represent the keys pressed or typed. The event listener corresponding to these types of event is the KeyListener.

The following example puts forth key event handling. The applet contains a label and a text field. The recently typed in character in the text field is displayed in the status bar. Example 4.

// Key events and KeyListener.
/*
<applet code = "keyTest.class" width = 400 height = 400>
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.Applet;
Public class keyTest extends Applet implements KeyListener
{
Public void init()
{
Label lab = new Label ("Enter Characters :");
add(lab);
TextField tf = new TextField(20);
add(tf);
tf.addKeyListener(this);
}
Public void keyPressed(KeyEvent e)
{}
Public void keyReleased(KeyEvent e)
{}
Public void keyTyped(KeyEvent e)
{
showStatus(" Recently typed characters are : " + e.getKeyChar());
}
}
Here the text field delegates its key events to the
applet. The add() method adds the components Label and TextField to the applet.

A quick recap: Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events.

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are typically components, but other kinds of objects can also be event sources. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.

In the next part of the tutorial we will see about Explicit Event-handling and adapters.

1 Mart 2010 Pazartesi

C# Event

Delegate ile ilgili makalemi okuyarak buradan okumaya devam ederseniz dünya daha güzel bir yer olabilir ;)

Event meselesini futboldan örnekle anlatmaya çalışayım.
Örneğin bir FutbolOyuncusu sınıfını düşün. Sahaya bu sınıftan 22 tane nesne yaratarak süreceksin. Her oyuncunun özellikleri, yeteneği, hızı, gücü farklı olacak.
- Golcü nesnesi(mesela Mario Gomez :) pozisyona girecek ve şut atmayı düşünecek ve keyfi bir hızla topu tepecek.
- Şut atıldığında bizim bir olayı tetiklememiz gerekiyor ki, diğer oyuncular buna göre pozisyon alsınlar.
- Ancak bu olay ayrıca Gomez'in o anda kaç km hızla topa vurduğu, açısını, zamanlamasını OnShoot olayına geçirmesini gerektirebilir.
- Olayın parametrelerine göre(hız, zaman, açı vs.) göre kaleci şutu görebilecek, topa uzanabilecek, tutacak ya da tokatlayacak.
- Olayın peşine, diğer nesneler(kaleci, rakip savunma, hücumcu oyuncular vs.) bir cevap üretebilmek için bu olayı takip ediyor olabilirler(bu olaya abone olabilirler).
- Ya da Mario atamaz diye hiç bir eylem içinde bulunmayabilir diğerleri.

* İşte OnShoot bizim EVENT'imiz(olayımız) anlaştık mı?
* OnShoot olayı anında bazı parametrelerimiz açığa çıkıyor (hız, açı, zamanlama vs.) bunlarda olay argumanları(Event Arguments).

Kod yazalım ve içindeki yorumlarımıza bakarak ilerleyelim:
using System;
using System.Data;
using System.Runtime;

namespace CSharp_Orneklerim.Delegate_Event
{
    public class Event_01
    {
        public static void Calis()
        {
            Topcu kaleciMuslera = new Topcu() { Adi = "Muslera" };
            Topcu cenkGonen = new Topcu() { Adi = "Cenk Gönen" };

            // Olaylara abone olacak nesnelerin fonksiyonlarını ekleyelim
            cenkGonen.OnShoot += (sutuVuranOyuncu, sutunOzelligi) =>
            {
                // Muslera hiçbir topu tutamasın ve top ağlarla buluşsun.
                if (!kaleciMuslera.Yakalamayi_Dene(sutunOzelligi))
                {
                    // TopunDurumu türünden dönecek sonucu 
                    // hakem gol olarak ilan edecek
                    Console.WriteLine("Muslera > - Ah Vah ah vah...");
                    return new TopunDurumu()
                           {
                               x1 = -2,
                               x2 = -2,
                               y1 = -2,
                               y2 = -2,
                               Hizi = 0
                           };
                }
                else
                {
                    // kaleci topu tekmeyle sahanın ortasına uzaklaştırsın
                    return new TopunDurumu()
                    {
                        x1 = 0,
                        y1 = 12,
                        x2 = 20,
                        y2 = 15,
                        Hizi = 20
                    };
                }
            };

            // herkes pozisyonunu aldı ve golcümüz ceza sahasına giriyor
            cenkGonen.Ceza_Sahasina_Topla_Gir();
        }
    }

    public partial class Topcu
    {
        /*
         * Çeşitli özellikleri olabilir
         * tackle : topu ayağından almak
         * speed : hız
         * size : boyut
         */
        public string Adi;

        /// <summary>
        /// Tüm oyuncular ceza sahasına girebilir(savunma, hücum vs.)
        /// Ancak davranışları elbette farklıdır. 
        /// Örneğin rakip hücumcu girerse kaleyi görüp şut çekerken,
        /// kendi ceza sahasına giren savunmacı uzaklaştırmak isteyecektir.
        /// Bu yüzden bu metodu virtual yapalım ki, Topcu sınıfını miras alacak başka sınıflar
        /// kendi isteklerine göre ezebilsinler.
        /// </summary>
        public virtual void Ceza_Sahasina_Topla_Gir()
        {
            /** 
             * Oyuncu topu ceza sahasına sürsün ve kaleyi görsün.
             * Şut çekecek ve bizim olayımız tetiklenecek
             * this oyuncumuz şutu çekti
             */
            Shoot shoot = new Shoot()
                          {
                              Aci = 60, // Topa 60 dereceyle 
                              Hiz = 50, // 50 km hızda 
                              Zaman = DateTime.Now, // şimdi vursun
                          };

            TopunDurumu durumu = veShoooot(shoot);
            // Şut atıldığında bir olayı(event) tetiklemek istiyoruz. 
            // Böylece bu olayı dinleyen tüm abonelere şut ile ilgili bilgi verebilelim
            // Görünüşe göre veShoooot metodu bu işi yapacak.
            // veShoooot metodu Shoot türünden bir değişken alsın ve topun durumunu dönsün
            // Bu metodu birazdan tanımlayacağız 
            // Ancak önce oluşturacağımız metodun dönen tipi ve parametrelerine bakalım
            //
            // 1 Parametre geçireceğiz bu metoda Shoot tipinde bir değişken
            // ve topun son durumu dönecek: {koordinatı, yönü, hızı} 
            //
            // Demekki Shoot ve TopunDurumu diye iki sınıfımızı yazmalıyız
        }
    }

    // 1. Shoot sınıfı
    public partial class Shoot
    {
        public int Aci, Hiz;
        public DateTime Zaman;
    }

    // 2. Topun durumu
    public class TopunDurumu
    {
        // iki nokta bir vektör tanımlar. konumu ve Yönünü bulduk.
        public int x1, y1, x2, y2, Hizi;
    }

    // 3. OnShoot olayı için method handler
    // OnShoot olayı(eventi) için bir delegate tipinde metot tutucu tipine ihtiyacımız var
    public delegate TopunDurumu Del_Donussuz_Shoot_Parametreli(Topcu _topcu, Shoot _shoot);

    // 4. Topcu sinifina OnShoot olayi tanımlama vakti geldi
    // OnShoot eventini Topcu sınıfına eklemeliyiz ki, tetikleyebilelim
    public partial class Topcu
    {
        // event tanımlamaları sınıf içinde yapılır ve ancak sınıftan tetiklenebilirler
        // event değikenlerine doğrudan bir atama(eventDegiskeni = null) yapılamaz
        // ancak += ya da -= ile atama yapılabilir
        public event Del_Donussuz_Shoot_Parametreli OnShoot;
        
        // Geldik OnShoot olayımızı tetikleme işini yapacak metodumuza.
        // Metodumuz event tetikleyecek. Event ancak sınıfın içinden tetiklenebilir, nesneden değil!
        // bu yüzden public erişim belirleyicisini kullanamayız.
        // Topcu sınıfından türetilen tiplerin de bu metodu çağırması gerekecek 
        protected virtual TopunDurumu veShoooot(Shoot shoot)
        {
            // OnShoot bizim tetikleyeceğimiz olayımız olacak(event)
            // OnShoot olayının tanımlandığı yerde varsayılan bir değer yok! Null kontrolü yapalım ! 
            if (OnShoot == null)
            {
                throw new NoNullAllowedException("OnShoot olayına hiç metot eklenmiş olmaz, olamaz!");
            } 
            return OnShoot(this, shoot);
        }

        /// <summary>
        /// Shoot parametresi ve kalecinin özellikleri arasında bir fonksiyonun sonucuna göre
        /// gol ise true, değilse false dönebilir. Ama burada kaleci Muslera ise kesin gol diyelim
        /// </summary>
        /// <param name="_shoot"></param>
        /// <returns></returns>
        public bool Yakalamayi_Dene(Shoot _shoot)
        {
            if (this.Adi == "Muslera")
            {
                return false; // tutamadı, gol
            }
            return true;
        }
    }

    /**
     * ----- YAPIYI ANLAYALIM:
     * Farkettiyseniz olayı tetiklendiğinde, bu olaya abonelere
     *   olayı kimin yaptığı,
     *   nasıl bir parametreyle gerçekleştiğini dönüyor
     *   Sonuçtada abonelerin topa müdahele edeceği düşünüldüğü için TopunDurumu
     *   tipinde bir sonuç değerini bekliyoruz.
     * 
     *           TopunDurumu OnShoot(Topcu sender, Shoot e) 
     *       
     * 
     * ----- GENEL DELEGATE TİPİ TANIMLAMAYA ÇALIŞALIM:
     * Bu OLAY TANIMINI genelleyerek şu metodu olay tutucu metodun imzası olarak elde edebiliriz:
     * 
     *             void On_BirŞey_Oldu(object sender, OlayParams e)
     *             
     *        
     * ----- GENEL OLAY PARAMETRE TİPİ TANIMLAMAYA ÇALIŞALIM
     * Bu metot tutucuyu şöyle yazabiliriz:
     * 
     *        delegate void OnDelegate(object sender, EventArgs e)
     *       
     * Bu tanımala gereği bizim EventArgs diye "genel olay parametreleri" tutan bir üst sınıfa ihtiyacımız var
     * Bu sınıftan kendi parametrelerimizi taşıyan sınıflar yaratarak aynı delegate tipini kullanabiliriz
     *  
     * ----- EVENTHANDLER TİPİ İŞİMİZİ GÖRECEK SANKİ
     * Yukarıdaki delegate tip tanımına uyan genel bir tip var adı: EventHandler tipi. 
     * Hem her olaya uygun olan EventArgs tipinde parametresi de var
     * 
     *      public delegate void EventHandler(object sender, System.EventArgs e)
     *      
     * Şeklinde tanımlı ve yukarıdaki imzaya uygun(void dönen ve iki parametre alan[object, EventArgs] metotlar için)
     * EventHandler tipini kullanabiliriz artık.
     */

    // ----- GENEL OLAY PARAMETRE TİPİ olan EventArgs'dan türesin olay parametre tipimiz
    public partial class Shoot : EventArgs { }

    /** 
     * Artık olay tanımımızı değiştirebiliriz
     */

    public partial class Topcu
    {
        // Başlangıç için boş bir isimsiz metodu değer olarak atadık ki 
        // eventi tetikleyeceğimiz yerde if(OnShoot2 != null){ OnShoot2(..) } null kontrolüne gerek kalmasın
        public event EventHandler OnShoot2 = delegate(object sender, EventArgs args) { };
    }
    /**
     * OnShoot2 metoduna parametre olacak gelen args değerleri Shoot türünden olabilir.
     * Ancak içeride bilinçli(explicit) cast(tür dönüşümü) etmeliyiz
     * 
     * kaleciMuslera.OnShoot2 += (sutuVuranOyuncu, sutunOzelligi) => Console.WriteLine(((Shoot)sutunOzelligi).Hiz);
     * 
     * gibi. 
     * Yada generic tip olan EventHandler<T> ile EventArgs türünden değil, kendi parametre türümüz olan Shoot türünden
     * bir method handler yaratmasını söylemeliyiz. 
     * 
     * Aşağıdaki gibi:
     */

    public partial class Topcu
    {
        // Generic tipli EventHandler'ı kullanarak bizim arguman tipimizden değerleri geçiriyor olağız.
        // eventi tetikleyeceğimiz yerde if(OnShoot3 != null){ OnShoot3(..) } null kontrolüne gerek kalmasın
        public event EventHandler<Shoot> OnShoot3 = delegate(object sender, Shoot args) { };
    }

    /**
     * Eğer Topcu sinifindan türeyen bir SolBek tipimiz olsa ve onun da OnShoot olayını tetiklemesi gerekse
     */

    public partial class SolBek : Topcu
    {
        public override void Ceza_Sahasina_Topla_Gir()
        {
            base.Ceza_Sahasina_Topla_Gir();
        }

        /// <summary>
        /// Sol beklerin şutu azıcık farklı olsun. 
        /// Mesela sol ayağına gelirse normal golcüden 2 kaplan daha güçlü vursun ;)
        /// </summary>
        public void SolAyaklaShoot()
        {
            // Topu düzeltsin,
            // Sol ayağına alsın, 
            // hede höde yapsın ve vursun. OnShoot olayı ata sınıftan tetikleneceği için
            // base.veShoooot metodunu çağırsın
            base.veShoooot(new Shoot()
                           {
                               Hiz = 100,
                               Aci = 70, //azicik yamuk vursun
                               Zaman = DateTime.Now
                           });

            // sonra ellerini başının arasına alsın,
            // Geri koşsun vs. vs....
        }
    }
}


Şimdi biz neden event diye bir
Çalışan hali
using System;
using System.Threading;

namespace caEvent1
{
public delegate void OnDemlendi();

class CayMakinasi
{
public CayMakinasi()
{
Console.WriteLine("Çay koyuldu...");
}

public event OnDemlendi eventDemlendi;

public void Demle()
{
Console.WriteLine();
Console.Write("Çay demleniyor ");
for (int i = 3; i > 0; i--)
{
Console.Write(".");
Thread.Sleep(1000);   
}
Console.WriteLine();
Demlendi();
}

private void Demlendi()
{
if (eventDemlendi!=null)
{
Console.WriteLine("  ---       DEMLİK İÇİNDE İŞLEMLER YAPILIYOR       --- ");
Console.WriteLine("  --- Demlikte işlem yapılıyor. Bitince haber verilecek");
Console.WriteLine("  --- ");
Console.Write("  --- Demleniyor");
for (int i = 3; i > 0; i--)
{
Thread.Sleep(3000);
Console.Write(".");
}
Console.WriteLine("  --- ");
Console.WriteLine("  --- Demlikten Haber VAR: <Çay demlendi>");
Console.WriteLine();
Console.WriteLine();
eventDemlendi();
}
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Çay yapmaya başlıyoruz...");
Console.WriteLine();

CayMakinasi cm = new CayMakinasi();
cm.eventDemlendi += new OnDemlendi(cm_OnDemlendi);

cm.Demle();

Console.WriteLine();
Console.WriteLine("Tavşan kanı bunlaaarrr...");
}

static void cm_OnDemlendi()
{
Console.WriteLine("**************************************************************");
Console.WriteLine("* Çayın olduğunda, makine metot işaretçisini tetikler.");
Console.WriteLine("* ");
Console.WriteLine("* O işaretçiyede kendi metodumuzu iliştiririzki ");
Console.WriteLine("* tam o sıra bizde işlemler yapabilelim.");
Console.WriteLine("* ");
Console.WriteLine("* Buna en güzel örnek, düğmeye tıklandığında işlem yapmamız");
Console.WriteLine("*  ya da GridView'a her satır eklendiğinde (RowDataBound) ");
Console.WriteLine("* satıra müdahale etme isteğimiz verilebilir.");
Console.WriteLine("**************************************************************");

}
}
}




Çalışan hali
using System;
using System.Threading;

namespace caEvent1
{
public delegate void OnDemlendi();

class CayMakinasi
{
public CayMakinasi()
{
Console.WriteLine("Çay koyuldu...");
}

public event OnDemlendi eventDemlendi;

public void Demle()
{
Console.WriteLine();
Console.Write("Çay demleniyor ");
for (int i = 3; i > 0; i--)
{
Console.Write(".");
Thread.Sleep(1000);   
}
Console.WriteLine();
Demlendi();
}

private void Demlendi()
{
if (eventDemlendi!=null)
{
Console.WriteLine();
Console.WriteLine("  *** Demlikten Haber VAR: <Çay demlendi>");
Console.WriteLine();
Console.WriteLine();
eventDemlendi();
}
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kahvehanede müşteri seslenir.");
Console.WriteLine("  - Garsooon 3 çaaay...!");
Thread.Sleep(1000);
Console.WriteLine("Garon cevap verir.");
Console.WriteLine("  - Taze yapıyorum Ali abicim...");

Thread.Sleep(1500);            
Console.WriteLine("Çay Makinesinin fişi takılır(nesne yaratılır),");
CayMakinasi cm = new CayMakinasi();

Thread.Sleep(4000);
Console.WriteLine("Çay olunca makine ötecek. Bizde bu sinyali duyar duymaz çay almaya gideceğiz.");
cm.eventDemlendi += new OnDemlendi(cm_OnDemlendi);

Thread.Sleep(2000);
Console.WriteLine("Çay Makinesinin ÇAY YAP düğmesine basılır(nesnenin metodu tetiklenir)");
cm.Demle();

Console.WriteLine("Tavşan kanı bunlaaarrr...");
}

static void cm_OnDemlendi()
{
Console.WriteLine("Garson makinenin başına gelir ve 3 çay koyar.");
Thread.Sleep(2500);
}
}
}

Peki birde metin okuyan ve "okuma tamamlandığında" olayında çalışan fonksiyon örneğiyle bir kod görelim:
using System;
using System.Speech.Synthesis;
using System.Threading;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer synthesizer = new SpeechSynthesizer();
            synthesizer.Volume = 100;  // 0...100
            synthesizer.Rate = -2;     // -10...10

            // Synchronous
            synthesizer.Speak("Merhaba Cem");
            synthesizer.SpeakCompleted += (a, b) =>
                                          {
                                              Console.WriteLine("Konuşma tamamlandı");
                                          };

            // Asynchronous
            var p = synthesizer.SpeakAsync("Asynchronous talk with Speak Async");
            while (!p.IsCompleted)
            {
                Console.WriteLine("Async function is still continuing");
                Thread.Sleep(100);
            }
            Console.WriteLine("End of Main Thread");
        }
    }
}