Getting started with gtk♯

Apr 08, 2010 17:15


Originally published at The Pædantic Programmer. Please leave any comments there.

This is a quick tutorial for getting a first gtk-sharp app up and going.
Install MonoDevelop

$ sudo apt-get install monodevelop libgtk2.0-cil-dev Start MonoDevelop

It’ll be in your GNOME application menu under Applications->Programming->MonoDevelop
Create a new Gtk# Project



Create New Project



Select Gtk# 2.0 Project



Select Project Features



Hello World
Run project

You can run this boilerplate by pressing Ctrl-F5
Using the Designer

Double-click on the file named MainWindow.cs in the Solution section. When the file opens, click the Designer button below the code view.



The Designer
The Toolbox

To add the Toolbox, press Alt-Shift-B or click View->Toolbox.

Drag a VBox widget from the Toolbox to the main window.



Add VBox

Drop a Menu Bar widget into the top cell of the VBox, and a Statusbar into the bottom.



Insert Menu and Status Bar
Properties grid

Drop a Button widget into the middle cell of the VBox.
Add the Properties grid from the View menu (Alt+Shift+P or View->Properties).
Select the new button by clicking on it.
In the Properties grid, expand the Button Properties section and click the value of the Label field. Delete the default content and replace it with a different string.



Button with new Label
Adding a Click handler

Select the button in the Designer view
In the Property grid, select the Signals tab
Click twice on the text in the column to the right of the Clicked and replace Click here to add a new handler with MyButtonClickHandler



Add a click handler

Click on the Source Code button below the viewer window to switch to the C♯ code. You can use the find tool to search for the new handler you created, called MyButtonClickHandler. Ctrl-F will bring up the find dialogue.



Browse to click handler

Add some code to update the status bar.

protected virtual void MyButtonClickHandler (object sender, System.EventArgs e) { var contextId = this.statusbar1.GetContextId("clicked"); this.statusbar1.Push(contextId, "Clicky-Clicky" ); }


Click handler code
Modify button layout

The size of the running window is a little weird. I fixed mine by un-setting the Auto Size boolean and setting the Expand and Fill in the Box Child Layout section of the Properties grid.



Button layout changes
Exercise button click handler

Run your application with Ctrl-F5 and click on the button. You should see the new string show up in the status bar at the bottom left of the window.



Not yet clicked



Clicked + Status update
Add Menu items



Create File Menu Entry



Create File->Quit Menu Item



Add Quit event handler



Add Clear Statusbar Activate Handler

c#, free software, gnome, washington state ubuntu loco, debian, ubuntu, gtk+

Previous post Next post
Up