Csharp/CSharp Tutorial/GUI Windows Forms/Event System

Материал из .Net Framework эксперт
Версия от 12:15, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Inference And Contravariance for Button Click, KeyPress, and MouseClick

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ruponentModel;
    class InferenceAndContravariance
    {
        static void LogPlainEvent(object sender, EventArgs e)
        {
            Console.WriteLine ("An event occurred");
        }
        static void Main()
        {
            Button button = new Button();
            button.Text = "Click me";
            button.Click += LogPlainEvent;
            button.KeyPress += LogPlainEvent;
            button.MouseClick += LogPlainEvent;
            Form form = new Form();
            form.AutoSize = true;
            form.Controls.Add(button);
            Application.Run(form);
        }
    }

Use .Net event system

using System;
public class SalaryEvent : EventArgs
{
  public string Message;
  public SalaryEvent(string message)
  {
    this.Message = message;
  }
}
public class Employee
{
  private int salary;
  public delegate void SalaryTaxEventHandler( object reactor, SalaryEvent myEvent );
  public event SalaryTaxEventHandler OnTax;
  public int Salary
  {
    set
    {
      salary = value;
      if (salary > 1000)
      {
        SalaryEvent myEvent = new SalaryEvent("Employee meltdown in progress!");
        OnTax(this, myEvent);
      }
    }
  }
}
public class EmployeeMonitor
{
  public EmployeeMonitor(Employee myEmployee)
  {
    myEmployee.OnTax += new Employee.SalaryTaxEventHandler(DisplayMessage);
  }
  public void DisplayMessage( object myEmployee, SalaryEvent myEvent )
  {
    Console.WriteLine(myEvent.Message);
  }
}

class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee();
    EmployeeMonitor myEmployeeMonitor = new EmployeeMonitor(myEmployee);
    myEmployee.Salary = 100;
    myEmployee.Salary = 500;
    myEmployee.Salary = 2000;
  }
}
Employee meltdown in progress!