Page 1
Windows Forms
zestaw narzędzi wspomagający tworzenie aplikacji okienkowych typu formularz + elementy sterujące
Project Windows Application
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;
Page 2
Hierarchia klas
Object
MarshalByRefObject
Component
Control
ScrollableControl
ContainerControl
Form
Page 3
Object podstawowa klas bazowa
MarshalByRefObject umożliwia
przetwarzanie formularza utworzonego
na odległym komputerze poprzez referencję
Component tworzy komponent ( kontener)
dla przechowywania obiektów
Control definiuje podstawowe cechy
formularza i podstawową obsługę zdarzeń
ScrollableControl umożliwia dodawanie
suwaków i przewijanie tekstu
ContainerControl umożliwia dziedziczenie
formularzy
Form składowe opisujące formularz
Page 4
namespace Empty{ public class Form1 : System.Windows.Forms.Form // partial
{ private System.ComponentModel. Containercomponents = null;
public Form1() {
InitializeComponent(); }
protected override void Dispose( bool disposing )
{ . . . }
Page 5
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300,300);
this.Text = ”Form1”; }
static void Main() { Application.Run(new Form1()); }
}}
Page 6
Form Designer dodawanie elementów sterujących
Properties ustalanie parametrów i obsługa zdarzeń
// klasa Form1
private System.Windows.Forms.Button Guzik_1;
// funkcja InitializeComponent
this.Guzik_1 = new System.Windows.Forms.Button();
FirstForm
Page 7
// Guzik_1 // dla zmienionych parametrów
this.Guzik_1.Location = new System.Drawing.Point(128, 104);
this.Guzik_1.Name = „Guzik_1”;this.Guzik_1.TabIndex = 0;this.Guzik_1.Text = „Czekam...”;this.Guzik_1.Click += new System.EventHandler(this.OnGuzik);
this.Controls.AddRange( new System.Windows.Forms.Control[] {this.Guzik_1});
// funkcja obsługiprivate void OnGuzik(object sender, System.EventArgs e)
{ .... } Nowy Guzik
Page 8
Obsługa myszy
zdarzenia związane z myszką
MouseClick MouseDoubleClick MouseDown
MouseEnter MouseHover
MouseMove MouseUp MouseLeave
Page 9
private void Form1_MouseDown
(object sender,
System.Windows.Forms.MouseEventArgs e);
{ ... }
składowe klasy MouseEventArgs
Button // left, middle, right
Clicks // liczba naciśnięć
Delta // liczba obrotów kółka
X , Y // współrzędne w momencie
// naciśnięcia
Page 10
Obsługa klawiatury
KeyDown KeyPress KyeUp
private void OnKey (object sender,
System.Windows.Forms.KeyEventArgs e);
{ ... }
składowe klasy KeyEventArgs
Alt, Control, Shift, Modifiers
KeyCode, KeyData, KeyValue
Form1.KeyPreview = true;
Page 11
Dodawanie menu
Form Designer wpisać nazwy pozycji menu
dla pozycji końcowych zdefiniować funkcje obsługi w oknie
Properties ( Events / Click ) i ewentualnie inne parametry
dekorowanie pozycji menu składowe klasy MenuItem
Checked, Enabled, ShortCut, ShowShortCut, Text
Page 12
Pasek stanu
dołączany za pomocą Form Designer, może zawierać różne rodzaje informacji
składowe klasy StatusStrip : StatusBar
ToolStripStatusLabel // tekstyToolStripProgressBar // postępToolStripDropDownButton // lista wyboruToolStripSplitButton
// przycisk i lista wyboru
Page 13
wyświetlanie podpowiedzi w panelu obsługa zdarzenia MouseEnter
( np. pozycji menu)
private void OnMouseEnter (object sender, System.EventArgs e)
{ toolStripStatusLabel1.Text =
"Kopiowanie.";
}
Page 14
wyłączanie podpowiedzi
private void OnMouseLeave (object sender, System.EventArgs e)
{
statusBarPanel1.Text = ".";
}
Page 15
Pasek narzędzi
za pomocą Form Designer dołączamy pasek obiekt ToolStrip
można dołączać i edytować poszczególne przyciski narzędzi ToolStripButton
dla przycisków można definiować opisy (Text) i dymki (ToolTipText)
obsługa naciśnięcia przcisku w oknie właściwości ToolStripButton dodać funkcję obsługi zdarzenia Click
Page 16
Elementy sterujące
kolejność zdarzeń generowanych przy
kontaktach z elementem sterującym:
Enter Leave
Validating Validated
gdy
CausesValidation == false
to zdarzenia Validating i Validated
nie są generowane
Page 17
Button przeciągnąć z przybornika, ustalić właściwości i
zdefiniować funkcje obsługi zdarzeń
private void Common_Button_Click
(object sender, EventArgs e)
{
Button bb = (Button)sender;
textBox1.Text = (string) bb.Tag;
}
Page 18
TextBox przeciągnąć z panelu elementów, ustalić właściwości (np. tekst początkowy), dodać obsługę zdarzeń np. TextChanged lub Leave
private void OnTextBox1Leave (object sender, System.EventArgs e)
{
string ss = textBox1.Text;
MessageBox.Show(ss);
}
można utworzyć pole dla wprowadzania hasła
można dodać suwaki przewijania
maskowanie MaskedTextBox
sprawdzanie poprawności
Page 19
Przyciski radiowe
aby uzyskać 1 z N należy najpierw umieścić GroupBox, a potem wewnątrz same przyciski
odczytanie stanu przycisku
if ( radioYellow.Checked )
{ ... }
Page 20
Dymki z podpowiedzią
przeciągnąć ToolTip z panelu (wyświetli się u dołu poza formularzem)
w oknie właściwości danego elementu wstawić tekst dymka np. do pola ToolTip on toolTip1
realizacja (automatyczna)
this.toolTip1.SetToolTip (this.radioButton1, "I am blue.");
Page 21
Przeciągnij i Upuść
Drag & Drop
źródło obsługa MouseDown
private void OnMouseDown(object sender, MouseEventArgs e)
{
TextBox tt = (TextBox)sender;
tt.SelectAll();
tt.DoDragDrop(tt.Text,
DragDropEffects.Copy);
}
Page 22
cel obsługa DragEnter
private void OnDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
Page 23
cel obsługa DragDrop
private void OnDragDrop(object sender, DragEventArgs e)
{
T2.Text += (string)e.Data.GetData(DataFormats.Text);
}
DraDro
Page 24
Schowek
(System.Clipboard – clipbrd.exe)
Clipboard.SetText(textBox.Text);
Clipboard.textBox.Copy(); // selected text
Clipboard.SetText((string)listBox.SelectedItem);
//
if(Clipboard.ContainsText())
textBox2.Text = Clipboard.GetText();
Page 25
//// obrazy .bmp
Bitmap bm = new Bitmap("P2.bmp");
Clipboard.SetImage(bm);
//
if (Clipboard.ContainsImage())
pictureBox1.Image = Clipboard.GetImage();
Page 26
///// dźwięki .wav
//
FileStream fs = new FileStream("notify.wav");
Clipboard.SetAudio(fs);
//
System.Media.SoundPlayer sp =
new SoundPlayer();
if (Clipboard.ContainsAudio())
{ sp.Stream = Clipboard.GetAudioStream();
sp.Load();
sp.Play(); }Clipboard
Page 27
Dalsze elementy sterujące
• NumericUpDown
• CheckBox // Checked
• DateTimePicker
• MonthCalendar
• ProgressBar
• ListBox
• ComboBox // DropDownList
• WebBrowser // Navigate
Page 28
• CheckedList
• TreeView
• ListView
• TabControl
• Chart
• TableLayoutPanel
• FlowLayoutPanel
• Timer
• BackGroundWorker
Chart, Prąd3Fazowy
Page 29
Powiązania ( bindings )
List<string> ll = new List<string>();
string[ ] ts = new string [ 5 ];
//
bindingSource1.DataSource = (object)ts;
bindingSource2.DataSource = (object)ll;
comboBox1.DataSource = (object)bindingSource1;
listBox1.DataSource = (object)bindingSource2;
//
bindingSource1.SuspendBinding();
bindingSource1.ResumeBinding();
bindingSource2.SuspendBinding();
bindingSource2.ResumeBinding(); DataBind
Page 30
Formularze wielojęzykowe
using System.Threading;
using System.Globalization;
using System.Resources;
using System.Reflection;
umieścić elementy na formie – teksty domyślne
ustawić Localizable = true wybrać język ( Language ) wpisać opisy wszystkich elementów dodać funkcję zmiany opisów
.....
Page 31
private void NewLang(string cul)
{ ComponentResourceManager crm =
new ComponentResourceManager(typeof(Form1));
CultureInfo ci = new CultureInfo(cul);
foreach (Control cc in this.Controls)
{
crm.ApplyResources(cc, cc.Name, ci );
if(cc.Controls != null)
for (int i = 0; i < cc.Controls.Count; ++i)
crm.ApplyResources(cc.Controls[i],
cc.Controls[i].Name, ci);
}}
Page 32
private void NewLang(string cul)
{
CultureInfo ci = new CultureInfo(cul);
Thread.CurrentThread.CurrentUICulture = ci;
rm = new ResourceManager("namespace.Form1", Assembly.GetExecutingAssembly());
button1.Text = rm.GetString("button1.Text");
label2.Text = rm.GetString("label2.Text");
.............
}
Page 33
Teksty z zasobów
pobrać:
ResourceManager rm2 = MLangTest.Properties.Resources.ResourceManager;
lub
Add -> New item -> Recources file ->
Resource1.resx
dodać nazwy tekstów i teksty
ResourceManager r1 = Resource1.ResourceManager;
textBox1.Text = r1.GetString("J2");
............ MuLan
Page 34
Okna dialogowe
dialogi standardowe osadzanie z panelu elementów poza formularzem
wyświetlanie i odczytywanie wyniku
string str ;
if (colorDialog1.ShowDialog() == DialogResult.OK)
{ str = colorDialog1.Color.ToString();
MessageBox.Show(str); }
// Color [A=255,R=139,G=201,B=98]
//
// filtr dla openFileDialog
openFileDialog1.Filter = "Program files|*.cs";
Dial
Page 35
Dialogi niestandardowe
utworzyć nowy formularz Dialog (Aplikacja/Add/Add Windows Form)
usunąć elementy ControlBox, MaximizeBox, MinimizeBox (false)
dodać przyciski OK i Cancel
i ustalić DialogResult
Page 36
w dowolnej funkcji (np. obsługa menu) dodać
Dialog dia = new Dialog();
dia.ShowDialog(); // modalny
dia.Show(); // nie modalny
do dialogu dodać dowolne elementy sterujące
wymiana danych poprzez obiekt dialogu np. dla ListBox CarMakes
CarMakes.SelectedIndex = 5; // 0,1,...
CarDialog.ShowDialog();
string str = CarMakes.Text; // modyfikator
dziedziczenie form (elementy bierne)
( Build Add Inherited Form )DzieForm
Page 37
Środowisko graficzne GDI+
przestrzenie nazw
System.Drawing System.Drawing.Drawing2D
System.Drawing.Imaging
System.Drawing.Printing
System.Drawing.Text
klasy pomocnicze
Point PointF Rectangle RectangleFSize SizeF
Region // rectangles + paths
Page 38
uzyskiwanie obiektu Graphics
- obsługa komunikatu Paint
private void OnMyPaint ( object sender, System.Windows.Forms.PaintEventArgs e )
{ Graphics g = e.Graphics; .... }
- z obrazu
Graphics g = Graphics.FromImage(pictureBox1.Image);
- z uchwytu
Graphics g = Graphics.FromHwnd(button1.Handle);
Page 39
unieważnianie obszaru klienta
Invalidate( ) Invalidate(Rect)
określanie koloru tła
Graphics g = e.Graphics;
e.Clear(Color.Yellow);
e.Clear(Color.FromArgb( 128, 255, 0, 0 ));
// (10, 200,120)
Paint1
Page 40
narzędzia graficzne :
czcionki
pióra
pędzle
definiowanie czcionki
Font f = new Font("Arial", 12,
FontStyleBold | FontStyleUnderline);
Page 41
definiowanie pióra
Pens.Firebrick // i inne kolory
Pen pen1 = new Pen(Color.Red, 5); // solid
// styl linii
pen1.DashStyle = DashStyle.Dash;
// .DashDot, .DashDotDot, .Dot, .Solid
//
// zakończenia linii
pen1.StartCap = LineCap.Flat;
pen1.EndCap = LineCap.Square;
// .Triangle, .ArrowAnchor, .RoundAnchor ...
Page 42
definiowanie pędzla
Brushes.Blue // i inne kolory
SolidBrush brush1 = new SolidBrush(Color.Red);
HatchBrush brush2 =
new HatchBrush( HatchStyle, linesColor, backColor);
LinearGradientBrush brush3 =
new LinearGradientBrush( Rectangle,
StartColor, EndColor ); // AnglePaint2
Page 43
wyprowadzanie tekstu
g.DrawString( string, Font, Brush, RectangleF | PointF, StringFormat );
Font f = new Font( "Tahoma", 40 );
g.DrawString( "Napis", f, Brushes.Red, 50, 50 );
//
StringFormat sf = new StringFormat();
sf.FormatFlags = StringFormatFlags.DirectionVertical;
g.DrawString("ALFA", f, Brushes.Green,
50, 50, sf );
Page 44
składowe klasy Graphics do rysowania (niektóre)
DrawLine
// Arc, Bezier, // Ellipse, Pie, Rectangle
FillEllipse
// Pie, Polygon, Rectangle
Page 45
kolekcja figur GraphicsPath
GraphicsPath gp = null;
Point[ ] T1 = { point1, point2, point3 };
Point[ ] T2 = { point4, point5, point6 };
//
gp = new GraphicsPath();
gp.AddPolygon(T1);
gp.AddPolygon(T2);
graphics.DrawPath(Pens.Red, gp);
Paint3
Page 46
przetwarzanie obrazów
string file = @"d:\Ob1.bmp";
Bitmap b1 = new Bitmap(file); // odczytywanie
pictureBox1.Image = b1; // wyświetlanie
//
b1.Save(@"d:\Ob2.jpg", // zapisywanie
System.Drawing.Imaging.ImageFormat.Jpeg);
Picture1
Page 47
przetwarzanie pikseli
Color px;
for (int x = 0; x < bitmap2.Width; ++x)
for (int y = 0; y < bitmap2.Height; ++y)
{
px = bitmap2.GetPixel(x, y);
if ( px ... )
bitmap2.SetPixel(x, y, Color.Red);
}
Picture2
Page 48
przetwarzanie obrazów GDI+
Bitmap bb = new Bitmap(350,200);
pictureBox1.Image = bb;
Graphics g =
Graphics.FromImage(pictureBox1.Image);
// draw, fill
bb = (Bitmap)pictureBox1.Image;
// process
pictureBox1.Image = bb;
Picture3