Windows Forms Quick Reference

This quick reference lists classes and methods that you can use to develop simple programs in Windows Forms. See the official API documentation (System.Drawing, System.Windows.Forms) for a complete reference.

All methods below are public unless otherwise specified.

== Index ==

== System.Drawing namespace ==

Bitmap : Image

The pixel data for a graphics image.

Bitmap (int width, int height);
Create an empty Bitmap with the given width and height in pixels.
Bitmap (string filename);
Load a Bitmap from a file containing an image in one of the following formats: BMP, GIF, EXIF, JPG, PNG or TIFF.
void Dispose();
Dispose a Bitmap when you are finished using it.
BitmapData LockBits (Rectangle rect, ImageLockMode flags, PixelFormat format);
Lock a bitmap's pixel data into memory so that you can access it directly. flags should be ImageLockMode.ReadWrite if you wish to read and write the pixel data. Typically format will be the image's own pixel format, which you can read from the PixelFormat property.
void UnlockBits (BitmapData bitmapdata);
Unlock a bitmap's pixel data when you are finished reading from and/or writing to it.

Brush : IDisposable

A color and/or pattern used to fill the interiors of graphical shapes.

Brushes

A class with read-only Brush objects representing various solid colors.

static Brush Black, Blue, Brown, Cyan, Gold, Gray, Green, Magenta, Maroon, Olive, Orange, Pink, Plum, Purple, Red, Silver, Tan, Violet, White, Yellow { get; }
Brush objects for standard colors. This is just a small selection; see the API documentation for a full list.

Color

An RGB (red, green, blue) color including an alpha (transparency) component.

static Color FromArgb (int red, int green, int blue);
static Color FromArgb (int alpha, int red, int green, int blue);
Construct a component from red, green, blue, and optional alpha components. Each component ranges from 0 to 255.
static Color Black, Blue, Brown, Cyan, Gold, Gray, Green, Magenta, Maroon, Olive, Orange, Pink, Plum, Purple, Red, Silver, Tan, Violet, White, Yellow { get; }
Standard colors. This is just a small selection; see the API documentation for a full list.

Font : IDisposable

A font family (such as "Times New Roman") plus size and style attributes.

Font (FontFamily family, float emSize);
Create a font with the given family and em-size in points. Call Dispose() to dispose the font's resources when you are finished using it.

FontFamily

A typeface such as Times New Roman.

static FontFamily GenericMonospace { get; }
static FontFamily GenericSansSerif { get; }
static FontFamily GenericSerif { get; }
Generic typefaces.

Graphics

A drawing surface. Typically you will use a Graphics object to draw on a window in the OnPaint handler of a Form subclass.

void DrawEllipse (Pen pen, int x, int y, int width, int height);
void DrawEllipse (Pen pen,
Rectangle rect);
Draw an ellipse defined by a bounding rectangle.
void DrawImage (Image image, int x, int y);
void DrawImage (Image image,
Point p);
void DrawImage (Image image, Rectangle r);
Draw an image at the specified location. If a Rectangle is passed, the image is scaled to fit in the given rectangle.
void DrawLine (Pen pen, int x1, int y1, int x2, int y2);
void DrawLine (Pen pen, Point p1, Point p2);
Draw a line between two points.
void DrawPolygon (Pen pen, Point[] points);
Draw a polygon whose vertices are given by an array of points.
void DrawRectangle (Pen pen, int x, int y, int width, int height);
void DrawRectangle (Pen pen,
Rectangle rect);
Draw a rectangle.
void DrawString (string s, Font font, Brush brush, Rectangle rect, StringFormat format);
Draw a string in the given Rectangle. The parameter format contains options indicating how text should be aligned in the rectangle.
void FillEllipse (Brush brush, int x, int y, int width, int height);
void FillEllipse (Brush brush,
Rectangle rect);
Fill an ellipse defined by a bounding rectangle.
void FillPolygon (Brush brush, Point[] points);
Fill a polygon whose vertices are given by an array of points.
void FillRectangle (Brush brush, int x, int y, int width, int height);
void FillRectangle (
Brush brush, Rectangle rect);
Fill a rectangle.
static Graphics FromImage (Image image);
Create a Graphics object that will draw on the given Image.
System.Drawing.Drawing2D.InterpolationMode InterpolationMode { get; set; }
Set the interpolation mode to be used for scaling images drawn with DrawImage(). The default mode Bilinear is relatively fast but produces poor results when shrinking an image below 50% of its original size. HighQualityBilinear is slower but can shrink images more nicely.
void RotateTransform (float angle);
Prepend a rotation in degrees to this Graphics object's transformation matrix.
void ScaleTransform (float sx, float sy);
Prepend a scaling transformation to this Graphics object's transformation matrix.
void TranslateTransform (float dx, float dy);
Prepend a translation to this Graphics object's transformation matrix.

Image : IDisposable

An abstract base class for images such as Bitmap objects.

int Height { get; }
This image's height in pixels.
PixelFormat PixelFormat { get; }
The format in which pixel data is stored.
ImageFormat RawFormat { get; }
The file format of this Image.
void RotateFlip (RotateFlipType rotateFlipType);
Rotate and/or flip an image. rotateFlipType is a constant such as Rotate90FlipX specifying the rotation and/or flip to perform; see the API documentation for a list of possible types.
void Save (string filename, System.Drawing.Imaging.ImageFormat format);
Save this image to a file in the given format.
int Width { get; }
This image's width in pixels.

Pen : IDisposable

A color and/or pattern used to draw lines and curves. Call Dispose() to dispose the pen's resources when you are finished using it.

Pen (Color color, float width);
Create a new Pen with the given color and width. If width is 0, the pen will draw as if the width were 1, even in the presence of a scaling transformation.

Pens

A class with read-only Pen objects.

static Pen Black, Blue, Brown, Cyan, Gold, Gray, Green, Magenta, Maroon, Olive, Orange, Pink, Plum, Purple, Red, Silver, Tan, Violet, White, Yellow { get; }
Pen objects for standard colors. This is just a small selection; see the API documentation for a full list.

Point

A pair of integers representing a geometric point.

Point (int x, int y);
Create a Point.
int X { get; set; }
int Y { get; set; }
Get or set the X- or Y-coordinate of this Point.
static Point operator + (Point pt, Size sz);
Translate a Point by a given Size.
static Point operator - (Point pt, Size sz);
Subtract a Size from a Point.

Rectangle

A geometric rectangle with a location and size.

Rectangle (int x, int y, int width, int height);
Rectangle (Point location, Size size);
Create a Rectangle with the given upper-left corner and size.
bool Contains (int x, int y);
bool Contains (Point point);
Return true if this Rectangle contains the given point.

Size

A pair of integers representing a width and height.

Size (int width, int height);
Create a Size.
int Height { get; set; }
int Width { get; set; }
Get or set the width or height of this Size.
static Size operator + (Size sz1, Size sz2);
Add two Size objects.
static Size operator - (Size sz1, Size sz2);
Subtract two Size objects.

SolidBrush : Brush

A brush that draws in a single color.

public SolidBrush (Color color);
Create a SolidBrush.

StringAlignment

An enumeration of values indicating how text should be aligned along a particular axis. The value StringAlignment.Center specifies that text should be centered.

StringFormat

A StringFormat object holds various options indicating how text should be drawn.

StringFormat ();
Create a StringFormat.
StringAlignment Alignment { get; set; }
Get or set the horizontal alignment.
StringAlignment LineAlignment { get; set; }
Get or set the vertical alignment.

== System.Drawing.Imaging namespace ==

BitmapData

Pixel data from a bitmap image.

int Height { get; set; }
The height of the data in pixels.
IntPtr Scan0 { get; set; }
A C pointer to the bytes of pixel data. You can access this data by using Marshal.Copy to copy it to/from a C# array, or by using unsafe C# language features that let you access unmanaged data directly.
int Stride { get; set; }
The number of bytes in each row of pixel data.
int Width { get; set; }
The width of the data in pixels.

ImageFormat

A enumeration of formats such as Jpeg or Png; see the API documentation for a complete list.

ImageLockMode

An enumeration of ways in which pixel data can be locked by the LockBits method in the Bitmap class. Typically you will use ImageLockMode.ReadWrite.

PixelFormat

An enumeration of value indicating formats in which low-level pixel data may be represented as bytes. For a photographic JPEG image, typically this will be Format24bppRgb, meaning that each pixel is stored in 24 bits, with 8 bits (= 1 byte) for each of red, blue, and green, and no alpha (transparency) channel. On Intel architectures color bytes appear in the order blue, green, red.

== System.Windows.Forms namespace ==

Application

A class with static methods for managing a graphical application.

static void Exit ();
Exit the application.
static void Run (Form mainForm);
Display a form and run the application's main loop.

Control

A component with a visual representation.

Color BackColor { get; set; }
Get or set the control's background color.
Control.ControlCollection Controls { get; }
Get the set of controls contained within the control. ControlCollection includes these methods:
void Add (Control value);

Add a control to the collection.

void Remove (Control value);

Remove a control from the collection.

bool Focus ();
Give the input focus to this control. The control with the focus will receive keyboard input. Returns true if the focus was set successfully.
Font Font { get; set; }
The font of the text displayed by the control, if any.
void Invalidate ();
Ask for the control to be redrawn. This will cause the system to call OnPaint() in the near future.
Point Location { get; set; }
Get or set the coordinates of the upper-left corner of the control relative to its parent.
static Keys ModifierKeys { get; }
Return a value indicating which modifier keys (e.g. Shift, Control) are currently pressed.
virtual void OnKeyDown (KeyEventArgs e);
virtual void OnKeyUp (KeyEventArgs e);
These methods run when the user has pressed (OnKeyDown) or released (OnKeyUp) a key. KeyEventArgs includes the following properties:
Keys KeyCode { get; }
The key that the user pressed or released.
virtual void OnKeyPress (KeyPressEventArgs e);
Runs when the user has pressed and released a key. KeyPressEventArgs includes the following properties:
bool Handled { get; set; }

If you set this field to true, then further event handlers will ignore the key press event since your code has already handled it.

char KeyChar { get; set; }

The character corresponding to the key that the user has pressed.

virtual void OnMouseDown (MouseEventArgs e);
virtual void OnMouseMove (MouseEventArgs e);
virtual void OnMouseUp (MouseEventArgs e);
Runs when the user has pressed a mouse button or moved the mouse. MouseEventArgs includes the following properties:
MouseButtons Button { get; }

The mouse button that was pressed. MouseButtons is an enumeration including values Left, Middle and Right.

Point Location { get; }

The mouse position, relative to the control reporting this event.

int X { get; }

The mouse's x-coordinate, relative to the control reporting this event.

int Y { get; }

The mouse's y-coordinate, relative to the control reporting this event.

virtual void OnPaint (PaintEventArgs e);
Runs when it is time to redraw the control. PaintEventArgs includes the following property:
Graphics Graphics { get; }

A Graphics object that should be used for painting.

virtual void OnResize (EventArgs e);
Runs when a control has been resized.
void SetBounds (int x, int y, int width, int height);
Set the position and size of the control.
Size Size { get; set; }
Get or set the height and width of the control.
string Text { get; set; }
Get or set the text associated with the control. (For a Form, this is the text that appears in the title bar.)

FileDialog

A standard dialog box for opening or saving a file. Subclasses include OpenFileDialog and SaveFileDialog. Call Dispose() to free a dialog box and its resources when you are finished using it.

string FileName { get; set; }
The filename selected in the dialog box.
DialogResult ShowDialog ();
Show a dialog box and return a result code indicating the button the user clicked to close the dialog. DialogResult is an enumeration including values OK and Cancel.

Form : Control

A window or dialog box.

The Text property (inherited from Control) holds the text in the window's title bar.

Form ();
Create a new form, i.e. a window.
Size ClientSize { get; set; }
The size of the form's client area.
bool KeyPreview { get; set; }
If true, the form will receive key events such as OnKeyDown even if another control has focus.
MainMenu Menu { get; set; }
The form's main menu.
DialogResult ShowDialog ();
Show a form as a modal dialog box.
FormStartPosition StartPosition { get; set; }
The form's initial position. FormStartPosition is an enumeration with values CenterScreen (the form appears in the center of the display) and Manual (the form's position is determined by its Location property).

Keys

An enumeration with codes for each key on the keyboard. Some values include

See the API documentation for a complete list.

MenuStrip

An form's main menu.

MenuStrip ();
Create a MenuStrip.
ToolStripItemCollection Items { get; }
Get the collection of items in this MenuStrip. You can add a ToolStripMenuItem to the collection by calling Items.Add(item).

MessageBox : Control

A dialog box that displays a message to the user.

static void Show (string text);
Display a message box with the specified text.

OpenFileDialog : FileDialog

A standard dialog box that prompts the user to open a file.

OpenFileDialog ();
Create an OpenFileDialog.

SaveFileDialog : FileDialog

A standard dialog box that prompts the user to save a file.

SaveFileDialog ();
Create a SaveFileDialog.

ScrollableControl : Control

A control that supports scrolling and can display scrollbars automatically.

virtual bool AutoScroll { get; set; }
Set this property to true to enable scrolling.
Size AutoScrollMinSize { get; set; }
Set the size of the virtual area through which the user can scroll.
Point AutoScrollPosition { get; set; }
Get or set the current scroll position. You must offset by this position when drawing in a ScrollableControl. You can do that as follows:

// Paint event handler
void onPaint(object sender, PaintEventArgs args) {
Graphics g = args.Graphics;
g.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y);

TextBox : Control

A TextBox displays one or more lines of text that the user can edit. Use the Text property (found in the Control superclass) to get or set the text in the box.

Timer

A Timer fires an event periodically.

Timer ();
Create a Timer.
bool Enabled { get; set; }
True if the timer is currently running. The default value is false.
int Interval { get; set; }
The timer interval in milliseconds.
event EventHandler Tick;
Occurs when the timer interval has elapsed.

ToolStripMenuItem

A ToolStripMenuItem is an item that appears in a menu. It may itself be a submenu, in which case it will contain a set of child ToolStripMenuItem objects.

ToolStripMenuItem (string text, Image image, EventHandler handler);
Create a ToolStripMenuItem that will run the given EventHandler when selected. image can be an image to display in this menu item, or null for none.
ToolStripMenuItem (string text, Image image, ToolStripMenuItem[] items);
Create a ToolStripMenuItem that represents a submenu and contains the given set of child menu items. image can be an image to display in this menu item, or null for none.
bool Enabled { get; set; }
If true, the menu item is enabled; if false, the menu item is grayed out and unavailable.