Gtk# 2 Quick Reference

This quick reference lists classes and methods that you can use to develop simple programs in Gtk# 2. For more information, see the official documentation.

All properties and methods below are public unless otherwise specified.

== Index ==

== Cairo namespace ==

Cairo is a library for drawing 2-dimensional graphics. GTK integrates closely with Cairo, and most GTK applications use Cairo for visual output.

Context : IDisposable

A Context is used for drawing graphics. Typically you will use a Context object to draw on a window in the OnExposeEvent handler of a Window subclass.

Be aware that methods such as Arc(), LineTo() and Rectangle() do not draw - they merely add a geometric shape to the current path. After you call these methods, you must call either Stroke() or Fill() to draw to the output surface.

Context (Surface surface)
Create a Cairo context that will draw on the given Surface.
void Arc (double x, double y, double radius, double angle1, double angle2);
Add an arc from angle1 to angle2 to the current path, centered at (x, y). To draw a circle, pass angle1 = 0.0 and angle2 = 2 * Math.PI.
void ClosePath ();
Close the current path, returning to its starting point.
void Fill ();
Fill in the current path with the current color.
void LineTo (double x, double y);
void LineTo (PointD p);
Add a line from the current point to the given point.
double LineWidth { set; get; }
Set or get the width of the stroke.
void MoveTo (double x, double y);
void MoveTo (PointD p);
Begin a new path at the given point.
void Paint();
Paint the current source everywhere in the the current clip region. Typically you will use this method for drawing an image that you have selected using CairoHelper.SetSourcePixbuf().
void Rectangle (double x, double y, double width, double height);
void Rectangle (Rectangle rectangle);
Add a rectangle to the current path.
void Scale (double sx, double sy);
Add a scaling transformation to the context's transformation matrix.
void SelectFontFace (string family, FontSlant slant, FontWeight weight);
Select a font to use for drawing text.
void SetFontSize (double scale);
Set the font size to use for drawing text.
void SetSourceRGB (double red, double green, double blue);
Set the color to be used for drawing to a Cairo context. (To set the color to a GDK color, see SetSourceColor, below.)
void SetSourceSurface (Surface source, int x, int y);
Set the given Surface as a source for drawing at the position (x, y) in the destination. Typically you will make a following call to Paint() to perform the actual drawing operation.
void ShowText (string text);
Draw text. The current position (the "reference point" or "origin") is at the left side of the text to be drawn, along the baseline, so the text will appear above and to the right of the current position.
void Stroke ();
Draw the current path without filling it.
TextExtents TextExtents (string text);
Get a TextExtents object with information about the size of the given text in the currently selected font.
void Translate (double tx, double ty);
Add a translation to the context's transformation matrix.

ImageSurface : Surface

An ImageSurface is a Cairo surface that holds pixel data in memory. You can draw onto an ImageSurface, and then later use the ImageSurface as a source for other drawing operations.

ImageSurface (Format format, int width, int height);
Create an ImageSurface with the given width and height. Typically Format will be either Format.Rgb24, meaning 24-bit color with 8 bits for each color channel (red, green, blue), or Format.Argb32, which is similar but also includes an 8-bit alpha (transparency) channel.

PointD

A PointD represents an (x, y) point. (The "D" stands for "double".)

PointD (double x, double y);
Construct a point from its x and y components.

Rectangle

A Rectangle represents a rectangle on the (x,y) plane. Note that this class (Cairo.Rectangle) is distinct from Gdk.Rectangle, which appears below.

Rectangle (double x, double y, double width, double height);
Construct a Rectangle.
double Height { get; }
double Width { get; }
double X { get; }
double Y { get; }
Retrive the components of a Rectangle.

Surface

Any kind of surface on which Cairo can draw.

TextExtents

A TextExtents structure represents layout information about a particular piece of text. Be aware that the values in this structure are sizes in screen pixels, independent of any coordinate transformation in the graphics context.

double Height { get; }
The height of the text.
double Width { get; }
The width of the text.
double XBearing { get; }
The horizontal distance from the origin (i.e. the point specified by MoveTo before a call to ShowText) to the leftmost part of the text glyphs.
double YBearing { get; }
The vertical distance from the origin to the topmost part of the text glyphs. Typically this will be negative.
In the image below, the red dot is the origin, and blue line represents the bearing. YBearing is negative, and XBearing is slightly negative:

Here is how to draw a string s centered at the point (x, y):

TextExtents te = context.TextExtents(s);
context.MoveTo(x - (te.Width / 2 + te.XBearing),
               y - (te.Height / 2 + te.YBearing));
context.ShowText(s);

== Gdk namespace ==

GDK is a low-level library that sits underneath GTK.

CairoHelper

This class contains a few static utility methods for working with Cairo.

static Cairo.Context Create (Gdk.Window window);
Create a Cairo context to draw on the given GDK window. When you are done drawing with the context, you should free it by calling Dispose().
static void SetSourceColor (Cairo.Context context, Color color);
Set the color to be used for drawing to the given Cairo context.
static void SetSourcePixbuf (Cairo.Context context, Pixbuf pixbuf, double x, double y);
Select a Pixbuf to use for drawing to a Cairo context at position (x, y). Typically you will follow this with a call to context.Paint() to draw the image.

Color

Color (byte red, byte green, byte blue);
Construct a color from the given red, green and blue components.
static bool Parse (string name, ref Color color);
Parse a given name, placing the result in the given Color. You can pass any X11 color name such as "red", "cornflower" or "dark slate gray". Alternatively, you can pass a string containing the red, green and blue components in hexadecimal; for example, "#3050b2" specifies the components red = 3016, green = 5016 and blue = b216. Returns true if the parse succeeded.

Pixbuf

A Pixbuf holds an image in memory. You can read a Pixbuf from a file and use Cairo to render it to the display.

Pixbuf (string filename);
Read a Pixbuf from a file in JPG, PNG or TIFF format. Throws an exception if the file is not found.
Pixbuf ApplyEmbeddedOrientation ();
Create a new Pixbuf in which the pixel data matches the orientation recorded by the camera for this image.
int BitsPerSample { get; }
The number of bits per color sample in this Pixbuf. This will usually be 8.
bool HasAlpha { get; }
True if this image includes an alpha channel.
int Height { get; }
The height of the image in pixels.
int NChannels { get; }
The number of channels of color data. This will be usually be 3 (for RGB encoding) or 4 (for RGB plus an alpha channel).
IntPtr Pixels { get; }
A pointer to the underlying C data that holds the image pixels. You may read or write the pixel data by copying it to/from a C# array using Marshal.Copy, or by using unsafe C# language constructs that let you access C data directly.
int Rowstride { get; }
The number of bytes in each row of pixel data. This may be NChannels * Width, but may be a larger value if there are padding bytes at the end of each row.
bool Save (string filename, string type);
Save the image to a file. type can be "jpeg" or "png". Return true if the save succeeded.
Pixbuf ScaleSimple (int dest_width, int dest_height, InterpType interp_type)
Resize an image to a new width and height, returning a new PixBuf. InterpType is an interpolation type, and can be e.g. InterpType.Bilinear for a reasonable balance between quality and speed, or InterpType.Hyper which produces a higher-quality image but is slower.
int Width { get; }
The width of the image in pixels.

Rectangle

A Rectangle represents a rectangle on the (x,y) plane. Note that this class (Gdk.Rectangle) is distinct from Cairo.Rectangle, which appears above.

Rectangle (int x, int y, int width, int height)
Construct a Rectangle.
public int Height;
public int Width;
public int X;
public int Y;
Retrive the components of a Rectangle.

== GLib namespace ==

Timeout

static uint Add (uint interval, TimeoutHandler handler);
Request that the given TimeoutHandler be called at regular intervals of interval milliseconds.

TimeoutHandler

delegate bool TimeoutHandler ();
Return true if calls to this TimeoutHandler should continue, or false to cancel the calls.

== Gtk namespace ==

Application

static void Init ();
Initialize GTK. Call this before calling any other GTK methods in your application.
static void Run ();
Run the application's main loop.
static void Quit ();
Quit the application.

Box : Widget

An HBox or VBox, used for arranging child widgets.

void PackStart (Widget child, bool expand, bool fill, uint padding);
Add a widget to a Box.
If expand is true, the child widget will expand to use as much space as it is given. If fill is true, the child widget will request as much space as is available. padding is the size (in pixels) of a border to place around the child widget.

Button : Widget

Button (string label);
Construct a Button with the given label.
event EventHandler Clicked;
Called when the user has clicked this button.

Dialog

A dialog box.

Dialog (string title, Window parent, DialogFlags flags, params object[] button_data)
Create a dialog box. flags will typically be DialogFlags.Modal to create a modal dialog. button_data indicates a set of buttons to display at the bottom of the dialog. Each such button is represented by a pair of values: a button text string (typically a stock string such as Stock.Add) followed by a value to be returned if that button is selected (typically a response code such as ResponseType.Ok or ResponseType.Cancel).
void Destroy ();
Destroy a dialog.
int Run ();
Run a dialog, returning when the user has chosen a response button. Typically the return value will a response code such as ResponseType.Accept or ResponseType.Cancel, cast to an int.
After a dialog returns, you must call Destroy() to destroy it - otherwise it will remain visible on the screen.

DrawingArea : Widget

A DrawingArea is a canvas where the program can draw graphics. Use a Cairo context to draw on a DrawingArea.

public DrawingArea ();
Create a DrawingArea.

FileChooserDialog : Dialog

A standard dialog box that prompts the user to select a file to be opened or created.

FileChooserDialog (string title, Window parent, FileChooserAction action, params object[] button_data)
Create a FileChooserDialog.
A typical call to this constructor might look like this:
new FileChooserDialog(
    "Open...", this, FileChooserAction.Open,
    Stock.Cancel, ResponseType.Cancel, Stock.Open, ResponseType.Accept);
string Filename { get; }
The filename that the user chose.

HBox : Box

An HBox contains one or more widgets that are arranged in a horizontal row.

HBox ();
Create an HBox.

Label : Widget

A widget that displays a text label, which is often a fixed string.

Label (string str)
Create a Label that will display the given string.

Menu

A top-level menu or submenu.

Menu ();
Create an empty Menu.
void Append (MenuItem child);
Add an item to this Menu.

MenuBar : Widget

The menu bar that appears at the top of a window.

MenuBar ();
Create an empty MenuBar.
void Append (MenuItem child);
Add an item that holds a top-level menu.

MenuItem : Widget

A MenuItem is an item that appears in a menu. It may itself contain a submenu of child MenuItem objects.

MenuItem (string label);
Create a MenuItem with the given label.
event EventHandler Activated;
An event that a MenuItem fires when the user selects it.
Menu Submenu { get; set; }
A submenu contained in this MenuItem.

VBox : Box

A VBox contains one or more widgets that are arranged in a vertical column.

VBox ();
Create a VBox.

Widget

A widget is a visual element such as a button, check box, scrollbar, or text area. (In Windows programming these are called controls, but "widget" is the usual Unix term.) A top-level window also counts as a widget.

void AddEvents (int events);
Ask to receive the given event(s). The events should be cast from a Gdk.EventMask, which is an enumeration with one value for each possible event type, including ButtonPressMask, ButtonReleaseMask and PointerMotionMask.
For example, if you want to receive all of these kinds of events, make this call:
AddEvents((int) (EventMask.ButtonPressMask |
                 EventMask.ButtonReleaseMask |
                 EventMask.PointerMotionMask));
Gdk.Rectangle Allocation { get; set; }
The Allocation property is a Gdk.Rectangle representing the widget's current size and position within its parent widget.
If this is a top-level widget, i.e. a Window, then Allocation.X and Allocation.Y will be 0, and Allocation.Width and Allocation.Height will be the size of the client area of the window.
void ModifyBg (StateType state, Gdk.Color color);
Modify the background color of this widget. Usually you will pass StateType.Normal as the first argument.
virtual bool OnButtonPressEvent (EventButton e);
virtual bool OnButtonReleaseEvent (EventButton e);
Called when the user has pressed or released a mouse button. An EventButton object has the following properties:
ModifierType State { get; }

A value indicating which modifier key(s) (e.g. Control, Shift) were held down as the mouse button was pressed. ModifierType is an enumeration including values ControlMask and ShiftMask.

EventType Type { get; }

One of the following values indicating the type of click:

Note that if the user double-clicks the mouse, you will receive a ButtonPress event for each click, and also a TwoButtonPress event.

double X { get; }
double Y { get; }

The X and Y coordinates of a button press, relative to the window.

Return true to indicate that the event has been handled.
event ExposeEventHandler ExposeEvent;
virtual bool OnExposeEvent (EventExpose e);
Runs when it is time for a widget to repaint itself.
An ExposeEventHandler has this signature:
delegate void ExposeEventHandler (object o, ExposeEventArgs args);
Typically the event handler will allocate a Cairo context and will use it to draw graphics:

using (Context c = CairoHelper.Create(GdkWindow)) {
    …
}

Return true to indicate that the event has been handled.
virtual bool OnKeyPressEvent (EventKey e);
Called when the user has pressed a key. An EventKey object has the following properties:
Gdk.Key Key { get; }

The key that the user pressed or released. Gdk.Key is an enumeration with one value for each physical key on a keyboard; for example, Gdk.Key.Left and Gdk.Key.Right are the left and right arrow keys, and Gdk.Key.Delete is the Delete key. See the full list of values here.

Return true to indicate that the event has been handled.
virtual bool OnMotionNotifyEvent (EventMotion e);
Called when the user has moved the mouse. An EventMotion object has the following properties:
double X { get; }
double Y { get; }

The X and Y coordinates of the mouse pointer, relative to the window.

Return true to indicate that the event has been handled.
virtual void OnSizeAllocated (Gdk.Rectangle allocation);
Called when this widget's size has changed. If this widget is a Window, this handler will be called when the user has resized the window.
bool Sensitive { get; set; }
If true, the widget is available. If false, the widget is grayed out and the user cannot interact with it.
void ShowAll ();
Show this widget and any widgets it contains.
void QueueDraw ();
Ask for this widget to be redrawn. This will cause the system to call the OnExposeEvent handler in the near future.

Window : Widget

A window that appears on the user's desktop.

Window (string title);
Construct a window with the given title. The window will not initially be visible; you must call ShowAll() to make it appear.
void Add (Widget widget);
Add the given widget to this Window. A Window can directly contain only a single widget; to hold more widgets, add a container widget such as a VBox and place the child widgets in that container.
virtual bool OnDeleteEvent (Gdk.Event evnt);
Called when the user has clicked a window's close button. Typically you will exit the application in reponse to this notification.
void Resize (int width, int height);
Set a window's width and height in pixels.
string Title { get; set; }
The window's title.