Вы находитесь на странице: 1из 101

WINDOWS

PROGRAMMING
WINDOWS FORMS & GDI+
WINDOWS FORMS
INTRODUCTION
WINDOWS FORMS (WINFORMS)
Part of .NET Framework for creating desktop applications:
System.Windows.Forms namespace
effectively a wrapper over part of Windows API

Categories of classes:
core infrastructure (e.g. Application, Form)
controls derived from the Control class (e.g. Button, TextBox)
components not derived from the Control class (e.g. Timer,
ToolTip)
common dialog boxes (e.g. OpenFileDialog, PrintDialog)

Karol Waldzik - Windows Programming 5


EVENT-HANDLING
Event-driven graphical user interface
Event handlers - methods that process events and perform tasks
Each control generating an event has an associated delegate that
defines the signature for event handlers
event delegates are multicast (they contain lists of method references)
once an event is raised, every method that the delegate references is called

Karol Waldzik - Windows Programming 6


EVENT-HANDLING EXAMPLE
public class MyForm : Form
{
public MyForm()
{
FormClosing += new FormClosingEventHandler(OnClosing);
}

private void OnClosing(Object sender,


FormClosingEventArgs e)
{
if (MessageBox.Show("Sure to close?", "Question",
MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
}

Karol Waldzik - Windows Programming 7


APPLICATION & FORM
APPLICATION
Class representing the entire Windows Forms application
Methods to
start and stop the application
i.e. start and stop the message loop
start and stop threads
process Windows messages
etc.

Properties with info about:


path to the executable file
path to application data directories
current culture
etc.

Karol Waldzik - Windows Programming 9


FORM
Class representing a main window, dialog box, or MDI child window
Inheritance hierarchy:
Object
MarshalByRefObject
Component
Control
ScrollableControl
ContainerControl
Form
Most members inherited from parent classes
(most notably Control class)

Karol Waldzik - Windows Programming 10


FORMS LIFETIME
1. Constructor
InitializeComponent()is called to create and initialize all child
controls added using the Form Designer (in Visual Studio)
2. Load
3. Activated
4. //...
5. FormClosing
6. FormClosed
7. [ Deactivate ]
8. Dispose (a part of the IDisposable interface)
use it for disposing any resources used by the form
9. Destructor (called by the Garbage Collector)

Karol Waldzik - Windows Programming 11


FORMS SIZE AND POSITION
Visibility
Show(), Visible
Shown, VisibleChanged

Properties:
Region, Bounds, DesktopBounds, ClientRectangle
Left, Top, Width, Height
Right = Left + Width
Bottom = Top + Height
StartPosition
Location, DesktopLocation
Size, ClientSize
MinimumSize, MaximumSize
AutoSize, AutoSizeMode
WindowState, TopMost

Karol Waldzik - Windows Programming 12


FORMS SIZE AND POSITION CONTD
Methods:
SetBounds(), SetDesktopBounds(),
SetDesktopLocation()
BringToFront(), SendToBack()
SizeFromClientSize()

Events:
ClientSizeChanged, SizeChanged
LocationChanged
MaximumSizeChanged, MinimumSizeChanged
Resize, ResizeBegin, ResizeEnd

Karol Waldzik - Windows Programming 13


FORMS APPEARANCE
Properties and methods for manipulating:
colors of different elements of the form
background images
fonts
icon, cursor icon
system buttons (minimize box, maximize box, help)
whether or not the form is visible
on the taskbar
opacity of the form
and more

Karol Waldzik - Windows Programming 14


MODEL AND MODELESS FORMS
Modal Modeless

Has to be closed before using the Allows to shift focus between


rest of the application different forms in the application

ShowModal() Show()
ShowDialog()

AcceptButton, Close()
CancelButton, FormClosing, FormClosed
DialogResult

Karol Waldzik - Windows Programming 15


CONTROLS:
BASE CLASSES
CONTROLS BASE CLASSES
Component - base class for all classes within the
System.Windows.Forms namespace
Control - message routing, keyboard and mouse, security, size
and position, HWND
Controls property - collection of child controls
ScrollableControl - auto-scrolling
ContainerControl - hosting other controls, focus, tab order
UserControl - composite control consisting of one or more
controls

Karol Waldzik - Windows Programming 17


CONTROL CLASSES HIERARCHY
Object
MarshalByRefObject
Component
ErrorProvider, ImageList, NotifyIcon, Timer, ToolTip, ...
Control

System.Windows.Forms
ButtonBase, Label, ListView, PictureBox, ProgressBar, ScrollBar,
TreeView, ...
ScrollableControl
Panel, ToolStrip
ContainerControl
PropertyGrid, SplitContainer, ToolStripContainer, ToolStripPanel, ...
UserControl
Form

Karol Waldzik - Windows Programming 18


CONTROL CLASS
Size and location
mostly the same as in Form
or, actually, the other way round

Auto-placement and auto-resize


Anchor position relative to the edge of its container
Dock

Z-order
BringToFront(),
SendToBack()

Karol Waldzik - Windows Programming 19


CONTROL CLASS CONTD
Styles:
SetStyle(), GetStyle(), UpdateStyles()
Tag allows associating custom data (of any type) with the control
Tabbing
TabStop
TabIndex

Focus
ControlStyles.Selectable

Karol Waldzik - Windows Programming 20


CONTROL CLASS CONTD
Parent-child relationships:
Controls collection of all child controls
HasChildren returns true if the control has child controls
Parent the control object that contains this control (may be null)
TopLevelControl - control at the very top of the controls hierarchy

Karol Waldzik - Windows Programming 21


CONTROL CLASS CONTD
Ambient properties
using parents values if not set
e.g. BackColor

To apply operating system visual theme to control


Application.EnableVisualStyles()
Accessibility support
Aim: application available for users with disabilities
AccessibleXXX

Karol Waldzik - Windows Programming 22


SCROLLABLECONTROL
Support for auto-scrolling behaviour
Enabling auto-scrolling:
1. AutoScroll = true
2. AutoScrollMinSize =

AutoScrollPosition
VScroll, HScroll visibility of scroll bars
Scroll event notification of scrolling

Usually not used directly:


use Panel instead

Karol Waldzik - Windows Programming 23


CONTAINERCONTROL
A control that can function as a container for other controls
Focus management
Useful properties:
ActiveControl
ParentForm

Karol Waldzik - Windows Programming 24


USERCONTROL
Composite controls
Reusable portions of the user interface
Similar to forms, but have no border, title bar and cannot be top-
level windows
Allow usage of standard controls with their functionality and
appearance

Karol Waldzik - Windows Programming 25


COMMON CONTROLS
COMMON CONTROLS TOOLBOX

Karol Waldzik - Windows Programming 27


LABELS
Label
read only text and/or image
usually description of a control or a form

LinkLabel
derived from Label
can display hyperlinks

Karol Waldzik - Windows Programming 28


TEXT CONTROLS
Used for text input (surprise ;-))
Derived From TextBoxBase
Keyboard shortcuts can be used (e.g. Ctrl+C, Ctrl +V)
TextBox
MaskedTextBox
Allows to control input format
RichTextBox
Text input control with
advanced formatting options

Karol Waldzik - Windows Programming 29


UPDOWNBASE (SPIN BOXES)
NumericUpDown
Value
Minimum, Maximum, Increment
DecimalPlaces, Hexadecimal, ThousandsSeparator
UpButton(), DownButton()

DomainUpDown
Sorted
Wrap
UpButton(), DownButton()

Karol Waldzik - Windows Programming 30


BUTTONS
ButtonBase
base class for Button, CheckBox, RadioButton
Button
PerformClick()
DialogResult
Mnemonics, e.g. "&Cut && Paste

CheckBox
Can have 2 or 3 check states (ThreeState)

Karol Waldzik - Windows Programming 31


LIST CONTROLS
Display lists of items in various graphical formats
Can be bound to a data source (more details later)
ListControl
base class for ListBox, CheckedListBox and ComboBox
Elements common to all list controls:
Items, Text, SelectedItem
Sorted
FindString(), FindStringExact()

Karol Waldzik - Windows Programming 32


LIST CONTROLS CONTD
ListBox
Single or multiple selection
CheckedListBox
derived from ListBox
multiple items can be checked
cant be bound to a data source

ComboBox
single selection
possibility to enter a new value

Karol Waldzik - Windows Programming 33


LISTVIEW
List of items (ListViewItem) + optionally
icons
check boxes
additional information

Several view modes


small icons
large icons
details

Karol Waldzik - Windows Programming 34


TREEVIEW
Used for displaying hierarchical data
Nodes can be expanded/collapsed
Nodes collection
Contains only top-level nodes
Each node has a collection of child nodes

Karol Waldzik - Windows Programming 35


DATE & TIME CONTROLS
DateTimePicker
customizable appearance
Format, CustomFormat
MinDate, MaxDate
ShowCheckBox, ShowUpDown
Value, Text
MonthCalendar
customizable appearance
MinDate, MaxDate, TodayDate
BoldedDates, MonthlyBoldedDates, AnnuallyBoldedDates
ShowToday, ShowTodayCircle, ShowWeekNumbers
SelectionStart, SelectionEnd, SelectionRange

Karol Waldzik - Windows Programming 36


OTHER USEFUL CONTROLS
PictureBox
including various resizing modes
ProgressBar
providing various display styles
WebBrowser
wrapper for the Internet Explorers ActiveX control
Url, Navigate()
GoBack(), GoForward(), GoHome(), GoSearch()
Navigating, Navigated, DocumentCompleted
C# - Javascript interoperation possible

Karol Waldzik - Windows Programming 37


BASIC GRAPHICAL COMPONENTS
ToolTip
SetToolTip(Control, string), GetToolTip
One tooltip can be assigned to multiple controls

NotifyIcon
Icon
ContextMenu
Text for icons tooltip
Visible

Karol Waldzik - Windows Programming 38


CONTAINERS
Panels
Panel
FlowLayoutPanel
dynamically lays out its content horizontally or vertically
TableLayoutPanel
lays out its contents in a grid

GroupBox
frame and caption around a group of controls
often used to group radio buttons

SplitContainer
two panels separated by a movable splitter

Karol Waldzik - Windows Programming 39


TABCONTROL
TabPages collection of TabPage objects
SelectedIndex, SelectedTab
SelectTab(), DeselectTab()
Deselecting, Deselected, Selecting, Selected

Karol Waldzik - Windows Programming 40


MENUS & TOOLBARS
MENUS & TOOLBARS TOOLBOX

ContextMenu

MainMenu

StatusBar

ToolBar

Karol Waldzik - Windows Programming 42


TOOLSTRIP & STATUSSTRIP
ToolStrip - represents a toolbar
StatusStrip represents a status bar
Can host various controls, e.g. dropdown, button, progress bar etc.
or custom controls
Advanced layout capabilities, e.g. overflow, docking and rafting

Karol Waldzik - Windows Programming 43


MENUSTRIP & CONTEXTMENUSTRIP
MenuStrip
derived from ToolStrip
hosts:
ToolStripMenuItem, ToolStripComboBox, ToolStripSeparator, ToolStripTextBox
Form.MainMenuStrip
ContextMenuStrip
derived from ToolStripDropDownMenu
Control.ContextMenuStrip

Mnemonics
Accelerators (independent of mnemonics):
ShortcutKeys, ShowShortcutKeys,
ShortcutKeyDisplayString
ToolStripManager, ToolStripRenderer

Karol Waldzik - Windows Programming 44


OTHER CONTROLS & COMPONENTS
BASIC COMPONENTS
Background worker
simplifies executing operations on background threads
DirectoryEnty, DirectorySearcher
encapsulate ActiveDirectory interactions
EventLog
provides access to Windows Event Log
FileSystemWatcher
provides notification about changes in the file system
HelpProvider
provides help
ImageList
manages a collection of images

Karol Waldzik - Windows Programming 46


BASIC COMPONENTS
PerformanceCounter
represents Windows performance counter
Process
allows process manipulation (e.g. starting and controlling external
applications)
SerialPort
represents serial port
ServiceController
allows Windows services manipulation
Timer
one of several timers available

Karol Waldzik - Windows Programming 47


VALIDATION
Control
CausesValidation
Validating (allows canceling), Validated

ContainerControl
AutoValidate
Validate(), ValidateChildren()

ErrorProvider
SetIconAlignment, SetIconPadding
BlinkStyle, BlinkRate
ContainerControl
(when used with data-bound control)
SetError(control, message)

Karol Waldzik - Windows Programming 48


DIALOGS TOOLBOX

Karol Waldzik - Windows Programming 49


OTHER TOOLBOX GROUPS
Printing support Reporting support

Database support for ADO.NET WPF Interoperability

Karol Waldzik - Windows Programming 50


DATA BINDING
DATA BINDING
Mechanism for connecting control properties with data
(one-way or two-way)
Simple binding: single values
Complex data binding: collections
Typical usage:
DataGridView and DataSet
DataSet
represents relational data (incl. tables and relations)
supports multiple data views
supports data changes tracking
DataGridView
designed for presentation and modification of tabular data
extensive support for binding - especially to DataSets and DataTables
DATA SOURCE
Simple binding
Control.DataBindings.Add
(propertyName, dataSource, dataMember)

Complex binding:
DataGridView
DataSource
DataMember
ListBox, ComboBox,
DataSource
DisplayMember, ValueMember, SelectedValue

Karol Waldzik - Windows Programming 53


DATA BINDING COMPONENTS
BindingSource
component encapsulating data source to simplify binding
(both simple & complex)
currency management
change notifications

ContainerControl.BindingContext
manages collection of instances of BindingManagerBase:
PropertyManagers for simple binding
CurrencyManagers for complex
binding

this.BindingContext[DataItems].Position += 1;

Karol Waldzik - Windows Programming 54


CUSTOM CONTROLS
CUSTOM CONTROLS
Composite control (user control)
composition of Windows Forms controls in a common container
(UserControl)
the only choice with design-time support

Extended control (derived control)


inherited from an existing Windows Forms control
functionality extended
OnPaint() method overriden to create a custom appearance

Custom control
inherited from one of the base control classes
Component, Control, ScrollableControl, ContainerControl
the most flexible (and the most time-consuming) way to create controls

Karol Waldzik - Windows Programming 56


VISUAL STUDIO SUPPORT
Every time a class library is compiled, Visual Studio scans through
the classes it contains, and adds each component or control to a
special temporary tab at the top of the Toolbox
The first time a control is added to a project (e.g. by dragging from
the Toolbox), Visual Studio:
adds a reference to the assembly where the control is defined
copies this assembly to the project directory

Toolbox can be customized


toolbox is a user-specific Visual Studio setting, not a project-specific setting

Karol Waldzik - Windows Programming 57


DESIGN TIME ISSUES
Easily add and configure the control at design time
Serializing control configuration steps into the form code (for
correct initialization at runtime)
Ensuring the control behaves properly at runtime (e.g. more or less
the same appearance as at design time)
Design-time shortcuts for complex configuration tasks
Using licensing to differentiate between development and runtime
use of a control, restricting use according to a custom license policy

Karol Waldzik - Windows Programming 58


DESIGN TIME SUPPORT
Control.DesignTime
Attributes:
supply information that will be used in the Properties window
attach other design-time components to the control and configure how
properties are serialized
Type converters
allow complex or unusual data types to be converted to and from
representations in more common data types
generate the initialization code required to instantiate a complex type

Type editors
provide graphical interfaces for setting complex type values

Karol Waldzik - Windows Programming 59


DESIGN TIME ATTRIBUTES
For classes:
DefaultPropertyAttribute
DefaultEventAttribute

For properties:
DefaultValueAttribute
EditorAttribute
LocalizableAttribute
TypeConverterAttribute

For properties and events:


BrowsableAttribute
CategoryAttribute
DescriptionAttribute

Karol Waldzik - Windows Programming 60


TYPECONVERTERS & UITYPEEDITORS
Custom TypeConverter overrides:
CanConvertFrom(), CanConvertTo()
ConvertFrom(), ConvertTo()
IsValid()

Custom UITypeEditor overrides:


EditValue(), GetEditStyle()
optionally: GetPaintValueSupported(), PaintValue()

Several dozen prebuilt implementations of both classes available

Karol Waldzik - Windows Programming 61


EDITING CUSTOM TYPES
Alternatives:
edit as a string - requires a TypeConverter
edit with a drop-down UI - requires a UITypeEditor
edit with a modal dialog box - requires a UITypeEditor

Karol Waldzik - Windows Programming 62


MOUSE & KEYBOARD
MOUSE
Mouse events
MouseMove, MouseDown, MouseUp, MouseClick, MouseDoubleClick
MouseEnter, MouseHover, MouseLeave, MouseWheel
Click, DoubleClick
MouseEventArgs:
{Button, Clicks, Delta, Location, X, Y}
Cursor class
can be loaded from a stream, file, program, or the systems resources
Form.Cursor
Cursors class standard cursors, e.g. Cursors.WaitCursor

Karol Waldzik - Windows Programming 64


KEYBOARD
Events:
KeyDown
KeyEventArgs:
{KeyCode, KeyData, Modifiers, Alt, Control, Shift, Handled, SuppressKeyPress)
KeyPress
KeyPressEventArgs:
{KeyChar, Handled}
KeyUp
KeyEventArgs

Keys enum
e.g. Keys.Q, Keys.F5, Keys.LShiftKey

Karol Waldzik - Windows Programming 65


FOCUS
Current focus:
CanFocus, Focused
ContainsFocus() (including children)
Focus()

Activating controls:
CanSelect
Select(), SelectNextControl()
Form.ActiveControl

Karol Waldzik - Windows Programming 66


FOCUS EVENTS

KEYBOARD / SELECT() MOUSE / FOCUS()


Enter Enter
GotFocus GotFocus
Leave LostFocus
Validating Leave
Validated Validating
LostFocus Validated

Karol Waldzik - Windows Programming 67


PREPROCESSING INPUT MESSAGES
PreProcessMessage
virtual method on Control class
messages pre-processed: WM_KEYDOWN, WM_SYSKEYDOWN, WM_CHAR,
WM_SYSCHAR
return:
true for processed messages
base.PreProcessMessage otherwise

More specialized methods:


IsInputChar(), IsInputKey()
ProcessCmdKey()
ProcessDialogChar(), ProcessDialogKey()

Karol Waldzik - Windows Programming 68


RESOURCES
RESOURCES
An assembly is a collection of types and optional resources
the binary data, text files, audio files, video files, string tables, icons,
images, XML files
Localized applications
a problem with multilingual user interface
for each resource added to an assembly, it is possible to specify the culture
information (a language and country, e.g. "pl-PL", "en-US", "de-De", "de-
AT")
satellite assemblies

Karol Waldzik - Windows Programming 70


TYPED RESOURCE FILES
Language=Polish
.txt Next=Nastpna strona
Prev=Poprzednia strona
textual name/value format
an easy way to add string resources

.resx
the XML format
support for both strings and other objects such as images

.resources
the binary format
a binary equivalent of the XML file
the only format that can be embedded in an assembly, the other formats
must be converted

Karol Waldzik - Windows Programming 71


CREATING .RESX FILES
ResXResourceWriter w =
new ResXResourceWriter(@"C:\myRes.resx");

Image img = new Bitmap("pattern.bmp");


w.AddResource("background", img);

w.AddResource("Next", "Nastpny");

w.Generate();
w.Close();

<?xml version="1.0" encoding="utf-8"?>


<root>
(...)
<data name="background"
type="System.Drawing.Bitmap, System.Drawing"
mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
Qk32BAAAAAAAAHYAAAAoAAAAMAAAADAAAAABAAQ
AAAAAAAAAAADDDgAAww4AABAAAAAQAAAAAAAA/w
...
</value>
Karol Waldzik - Windows Programming 72
CREATING .RESOURCES FILES
From .resx or .txt file
resgen myRes.resx myRes.resources
resgen polish.txt polish.resources

Using C#
ResourceWriter rw =
new ResourceWriter(@"C:\myRes.resources");

Image img = new Bitmap("pattern.bmp");


w.AddResource("background", img);

w.AddResource("HelloWorld", "Witaj wiecie");

w.Generate();
w.Close();

Karol Waldzik - Windows Programming 73


RETRIEVING RESOURCES

ResourceManager rm =
new ResourceManager("myApp.myRes",
Assembly.GetExecutingAssembly());

MessageBox.Show(rm.GetString("HelloWorld"));

pictureBox.Image =
(Bitmap)rm.GetObject("background");

rm.ReleaseAllResources();

Karol Waldzik - Windows Programming 74


RESOURCES WITH VISUAL STUDIO
Adding resources
in resx files:
Project > Add New Item > Resources File
or: Project > Properties > Resources
a property in a special class is generated for easier access to resource

Editing resources
Visual Studio built-in editors
the binary editor, image editor
external editors (e.g. the Paint for image files)
other applications can be associated with types of resources

Compiling resources into assemblies


resgen.exe tool is called automatically

Karol Waldzik - Windows Programming 75


USING THE SOURCE CODE GENERATED BY VS
public class Resource1
{
public static string String1
{
get { return ResourceManager.GetString(
"String1", resourceCulture); }
}
public static System.Drawing.Bitmap FeatherTexture
{
get
{
object obj = ResourceManager.GetObject(
"FeatherTexture", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
} pictureBox1.Image = Resource1.FeatherTexture;
label1.Text = Resource1.String1;
Karol Waldzik - Windows Programming 76
LOCALIZING APPLICATIONS
Retrieved resources language:
ResourcesManager.Get...(name, culture)
Thread.CurrentUICulture
VS-generated helper class:
Resources.Culture

Default data formatting language:


Thread.CurrentCulture
Keyboard input language:
InputLanguage.InstalledInputLanguages, InputLanguage.DefaultInputLanguage,
InputLanguage.CurrentInputLanguage
Application.CurrentInputLanguage

Karol Waldzik - Windows Programming 77


MANIFEST RESOURCES
Another method for embedding resources in assembly
without use of .resource files
all resources stored as untyped binary data

Adding resource:
add file to the project
in its Properties, set Build Action: Embedded Resource

Retrieving resource:
Assembly.GetManifestResourceStream
type-specific methods
e.g. one of Bitmap class constructors
APPLICATION SETTINGS
APPLICATION SETTINGS
THE OLD WAY
.config files (XML)
special naming convention [executableFileName].config
can be read and modified by applications

<configuration>
<appSettings>
<add key="welcome" value="Hello, user!"/>
<add key=bye" value=Farewell!"/>
</appSettings>
</configuration>

AppSettingsReader reader = new AppSettingsReader();


string s = (string)reader.GetValue("welcome,
typeof(string));

Karol Waldzik - Windows Programming 81


APPLICATION SETTINGS THE NEW (STRONGLY TYPED) WAY
<configuration>
<configSections>
<sectionGroup name="userSettings
type="System.Configuration.UserSettingsGroup, System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Tests.Settings1
type="System.Configuration.ClientSettingsSection, System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
allowExeDefinition="MachineToLocalUser"
requirePermission="false" />
</sectionGroup>
<sectionGroup name="applicationSettings
type="System.Configuration.ApplicationSettingsGroup, System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Tests.Settings1
type="System.Configuration.ClientSettingsSection, System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
requirePermission="false" />
</sectionGroup>
</configSections>
...
</configuration>

Karol Waldzik - Windows Programming 82


APPLICATION SETTINGS THE NEW (STRONGLY TYPED) WAY

<configuration>
...
<userSettings>
<Tests.Settings1>
<setting name="Setting1" serializeAs="String">
<value>test</value>
</setting>
</Tests.Settings1>
</userSettings>
<applicationSettings>
<Tests.Settings1>
<setting name="Setting2" serializeAs="String">
<value>test2</value>
</setting>
</Tests.Settings1>
</applicationSettings>
</configuration>

Karol Waldzik - Windows Programming 83


APPLICATION SETTINGS THE NEW WAY VS SUPPORT

Defined in separate .settings files

var setting2Value = Settings1.Default.Setting2;


Settings1.Default.Setting1 = "Test";
DateTime time = Settings1.Default.Setting3;
Karol Waldzik - Windows Programming 84
MESSAGE HANDLING HOOKS
APPLICATION.ADDMESSAGEFILTER()

public class TestMessageFilter : IMessageFilter


{
public bool PreFilterMessage(ref Message m)
{
//Blocks all the messages relating
//to the left mouse button.
if (m.Msg >= 513 && m.Msg <= 515)
{
Console.WriteLine("Processing the messages :
+ m.Msg);
return true;
}
return false;
}
}
Application.AddMessageFilter(new TestMessageFilter());

Karol Waldzik - Windows Programming 86


OVERRIDING WINDOW PROCEDURE
Message: {HWnd, LParam, Msg, Result, WParam}
Form.Handle HWND

private const int HTCAPTION = 0x0002;


private const int WM_NCHITTEST = 0x0084;

protected override void WndProc(ref Message m)


{
switch (m.Msg)
{
case WM_NCHITTEST:
m.Result = (IntPtr)HTCAPTION;
break;
default:
base.WndProc (ref m);
break;
}
}

Karol Waldzik - Windows Programming 87


GDI+
GDI+
Successor to Windows Graphics Device Interface (GDI)
supports GDI for compatibility with existing applications
optimizes many of the capabilities of GDI
provides additional features

Class-based application programming interface (API)


two independent implementations: .NET (managed code) and unmanaged
code
Availability:
included in Windows XP+ and Windows Server 2003+
redistributable for NT 4.0 SP6, 2000, 98, Me
Gdiplus.dll

Karol Waldzik - Windows Programming 89


NEW FEATURES
Gradient brushes (linear and path)
for filling shapes, paths and regions
Cardinal splines
Independent path objects (GraphicsPath objects)
Transformations, Matrix object
Transformations of regions
Alpha blending
Image formats:
BMP, GIF, JPEG, Exif, PNG, TIFF, ICON, WMF, EMF

Karol Waldzik - Windows Programming 90


GRAPHICS CLASS
Graphics class:
core of GDI+
Device Context equivalent
associated with a particular window on the screen
contains attributes that specify how items are to be drawn
improvements (compared to DC):
less state:
pens, brushes, paths, images, and fonts as method parameters
no current position for drawing lines
separate methods for draw and fill

GDI object equivalents:


represented as true objects
in .NET: implement IDisposable

Karol Waldzik - Windows Programming 91


USING GRAPHICS
Obtaining Graphics object:
Paint event handler: PaintEventArgs.Graphics
Control.CreateGraphics()
Graphics: FromHdc(), FromHwnd(), FromImage()

Triggering the Paint Event:


Control.Invalidate()
Control.Update(), Control.Refresh()

Flicker-free drawing: this.DoubleBuffered = true

private void AboutForm_Paint(object sender, PaintEventArgs e)


{
e.Graphics.FillRectangle(Brushes.White, 0, 0, 200, 100);
using (Pen mP = new Pen(Color.Red, 3)) {
e.Graphics.DrawLine(mP, 20, 10, 90, 90);
}
}
Karol Waldzik - Windows Programming 92
SIMPLE SHAPES
Simple figures:
DrawLine(), DrawRectangle(), DrawEllipse(), DrawArc(), DrawPolygon()
FillEllipse(), FillPie(), FillPolygon(), FillRectangle()

Cardinal splines:
DrawCurve(), DrawClosedCurve()
FillClosedCurve()

Bezier splines:
DrawBezier(), DrawBeziers()

Karol Waldzik - Windows Programming 93


PATHS
Formed by combining lines, rectangles, and simple curves
GraphicsPath class:
adding simple figures:
AddLine(), AddRectangle(), AddEllipse(), AddArc(), AddPie(), AddBezier(),
AddCurve(), AddClosedCurve(), AddPolygon(), AddString()
joining two paths: AddPath()

Graphics.DrawPath()
Graphics.FillPath()

Karol Waldzik - Windows Programming 94


REGIONS
Describe interiors of graphics shapes composed of rectangles and
paths
Region class
Hit testing
Region.IsVisible(point, graphics)
Clipping
Graphics.SetClip(region)

Karol Waldzik - Windows Programming 95


BRUSHES
Brush abstract base class for all brushes:
SolidBrush, HatchBrush, TextureBrush, LinearGradientBrush,
PathGradientBrush

using (SolidBrush solidBrush =


new SolidBrush(Color.FromArgb(255, 255, 0, 0))) {
e.Graphics.FillEllipse(solidBrush,0,0,100,60);
}

using (HatchBrush hBrush =


new HatchBrush(HatchStyle.Horizontal,
Color.Green, Color.Blue) {
e.Graphics.FillEllipse(hBrush,100,0,100,60);
}

Image image = new Bitmap("texture.jpg");


TextureBrush tBrush = new TextureBrush(image);
e.Graphics.FillEllipse(tBrush,200,0,100,60);

Karol Waldzik - Windows Programming 96


PENS
Attributes
Width
Alignment (PenAlignment enumeration)
Line caps:
StartCap, EndCap (LineCap enumeration)
CustomStartCap, CustomEndCap (CustomLineCap class)
LineJoin (LineJoin enumeration)
DashStyle, DashPattern, DashCap
Brush

var image = Image.FromFile("texture.jpg");


var Brush = new TextureBrush(image);
var texturedPen = new Pen(tBrush, 30);
e.Graphics.DrawLine(texturedPen, 0, 0, 50, 50);

Karol Waldzik - Windows Programming 97


IMAGES
Image abstract base class
Bitmap derived from Image
contains specialized methods for loading, displaying, and manipulating
raster images
Graphics.DrawImage()
many overrides available
flexible resizing/cropping possibilites
influenced by Graphics.InterpolationMode
influenced by Graphics.Transform

Karol Waldzik - Windows Programming 98


IMAGE ENCODERS/DECODERS
Listing installed encoders and decoders:
ImageCodecInfo.GetImageEncoders(),
ImageCodecInfo.GetImageDecoders()
return arrays of ImageCodecInfo

public void ConvertImage(string srcPath, string destPath,


ImageFormat destFormat)
{
Image image = new Bitmap(srcPath);
image.Save(destPath, destFormat);
}

try {
ConvertImage(bird.jpg, bird.png, ImageFormat.Png);
}
catch (Exception exc) { }
Karol Waldzik - Windows Programming 99
TEXT
Graphics.DrawString()
at specified location
in a rectangle
StringFormat argument:
Alignment, LineAlignment
SetTabStops()
FormatFlags
TextRenderingHint allows switching on antialiasing

Karol Waldzik - Windows Programming 100


FONTS
Font class
Metrics
Font.GetSize()
FontFamily.GetEmHeight()
FontFamily.GetCellAscent()
FontFamily.GetCellDescent()
FontFamily.GetLineSpacing()

Font font = new Font("Arial", 16,


FontStyle.Regular);

Karol Waldzik - Windows Programming 101


TRANSFORMATIONS
Matrix class
Graphics.Transform
helper methods:
ScaleTransform()
RotateTransform()
TranslateTransform()

Transformation order is significant

Karol Waldzik - Windows Programming 102


GRAPHICS CONTAINERS
GraphicsContainer class
Stores state of Graphics:
link to device context
quality settings
transformations
clipping region
Pen pen = new Pen(Color.Red);
Alternative: gr.TranslateTransform(100.0f, 80.0f);
Graphics.Save()
GraphicsContainer
graphicsContainer = gr.BeginContainer();
gr.RotateTransform(30.0f);
gr.DrawRectangle(pen,-60,-30,120,60);
gr.EndContainer(graphicsContainer);

gr.DrawRectangle(pen,-60,-30,120,60);

Karol Waldzik - Windows Programming 103

Вам также может понравиться