Novell Home

Custom event (full example)

From Developer Community

The emission and the treatment of a custom event. Very simple to understand.

The most important thing to know is : An event must be captured by at least one object, it's why every Gtk element that as an event like "Clicked" as a protected method "OnClicked".

Event.cs

// Event.cs

// Playing with lists !
// Copyright 2005, Yoan BLANC <yoan @ dosimple.ch>, HE-ARC (he-arc.ch)
//
// distibuted under the GPLv2 : http://opensource.org/licenses/gpl-license.php

using Gtk;
using System;

// main app
public class Event
{
	public static void Main(string[] args)
	{
		Application.Init();
		
		new EventTest("Event test");
		
		Application.Run();
	}
}

// the window
public class EventTest : Window
{
	public event LabelEventHandler ButtonClicked;
	
	public EventTest(string title) : base(title)
	{		
		DeleteEvent += Window_Delete;
		ButtonClicked += OnButtonClicked;
		
		VBox v = new VBox();
		v.BorderWidth = 6;
		
		// --
		
		Button a = new Button("a");
		Button b = new Button("b");
		Button c = new Button("c");
		
		a.Clicked += onClick;
		b.Clicked += onClick;
		c.Clicked += onClick;
		
		v.Add(a);
		v.Add(b);
		v.Add(c);
		
		// --
		
		ButtonClicked += myOnButtonClicked;
		
		// --
		
		Add(v);
		ShowAll();
	}
	
	// recieve the click, emit the label
	private void onClick(object sender, EventArgs args)
	{
		LabelEventArgs largs = new LabelEventArgs(((Button)sender).Label);

		ButtonClicked(this, largs);
	}
	
	protected void OnButtonClicked(object sender, EventArgs args)
	{
		// pass
	}

	// recieve the label
	private void myOnButtonClicked(object sender, LabelEventArgs args)
	{
		Console.WriteLine(args.Label + " clicked !");
	}
	
	// close the window
	private static void Window_Delete (System.Object o, DeleteEventArgs args)
	{
		Application.Quit ();
		args.RetVal = true;
	}
}

// the handler
public delegate void LabelEventHandler (object sender, LabelEventArgs e);

// my event args
public class LabelEventArgs : EventArgs
{
	public string Label
	{
		get
		{
			return _label;
		}
	}
	
	public LabelEventArgs (string label) : base()
	{
		_label = label;
	}
	
	private string _label;
}

--Yoan Blanc

Novell® Making IT Work As One

© 2009 Novell, Inc. All Rights Reserved.