Mono coding: Capturing right clicks in a Gtk.TreeView
I had a hard time figuring out how to capture a right click on a TreeView, which I needed to be able to make a context menu or popup menu or whatever you wanna call it.
The way I expected it would work didn’t… I think it have something to do with a change in Mono some time ago (Why don’t I get ButtonPressEvents from my Button/Treeview?).
This example is based on the “Shortcuts - Writing Less Code” example from the www.mono-project.com website. The main difference is that the TreeView is no longer setup in the main class but is now a separate class with the function OnButtonPressEvent
overwritten.
public class TreeViewExample {
public static void Main ()
{
Gtk.Application.Init ();
new TreeViewExample ();
Gtk.Application.Run ();
}
public TreeViewExample ()
{
Gtk.Window window = new Gtk.Window ("TreeView Example");
window.SetSizeRequest (500,200);
MusicTreeView tree = new MusicTreeView ();
window.Add (tree);
window.ShowAll ();
}
}
// Creating a new class MusicTreeView which is derived from the TreeView class
public class MusicTreeView : Gtk.TreeView {
public MusicTreeView ()
{
Gtk.ListStore musicListStore = new Gtk.ListStore (typeof (string), typeof (string));
this.AppendColumn ("Artist", new Gtk.CellRendererText (), "text", 0);
this.AppendColumn ("Title", new Gtk.CellRendererText (), "text", 1);
musicListStore.AppendValues ("Garbage", "Dog New Tricks");
this.Model = musicListStore;
}
// The TreeView has a build in function which is called upon a OnButtonPressEvent
// We override the function to capture right clicks with the mouse
protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
{
if(evnt.Button == 3) {
System.Console.WriteLine ("Right click");
return true;
}
// Now if we would ever get this far
// we run the TreeViews OnButtonPressEvent function
// to make sure everything else works as normal
return base.OnButtonPressEvent(evnt);
}
}
Update: I wrote a new “right click in Gtk.TreeView” example.
Mono coding: Capturing right clicks in a Gtk.TreeView
© 2007 by Jacob Emcken is licensed under CC BY-SA 4.0