78
Hochschule Harz FB Automatisierung und Informatik Seite 1 Fachbereich Automatisierung und Informatik Wernigerode „Visual Studio mit C# Grundlagen Stand 31.01.2009 Dipl. Inf., Dipl.-Ing. (FH) Michael Wilhelm Friedrichstraße 57 - 59 38855 Wernigerode Raum: 2.202 Tel.: 03943/659-338 Fax: 03943/659-399 Email: [email protected]

„Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

  • Upload
    others

  • View
    1

  • Download
    1

Embed Size (px)

Citation preview

Page 1: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 1

Fachbereich Automatisierung und Informatik

Wernigerode

„Visual Studio

mit C#

Grundlagen

Stand

31.01.2009

Dipl. Inf., Dipl.-Ing. (FH) Michael Wilhelm Friedrichstraße 57 - 59 38855 Wernigerode Raum: 2.202 Tel.: 03943/659-338 Fax: 03943/659-399 Email: [email protected]

Page 2: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 2

Inhaltsverzeichnis 1 Einführung in .net und C#................................................................................................................ 5

1.1 Überblick 5 1.1.1 C# 5 1.1.2 .net 5

1.2 Eigenschaften 5 2 Beispiele........................................................................................................................................... 7

2.1 Hello World 7 3 Syntax............................................................................................................................................... 8

3.1 Datentypen in C# 8 3.2 String-Befehle 8 3.3 C# Sprache 9

3.3.1 Switch-case 9 3.4 foreach 10 3.5 Enumerationen 10 3.6 Ausgabe in der Console 12 3.7 Eingabe von der Console 12

3.7.1 Formatierte Ausgaben 12 3.8 Parameter-Übergabe 13 3.9 Delegates 14 3.10 Try Catch 15

4 Objektorientierte Programmierung ................................................................................................ 16 4.1 Konstruktor 16 4.2 Dekonstruktor 16 4.3 sealed 16 4.4 Set-Get-Methoden 17 4.5 Überschriebene Methoden 17

4.5.1 Prinzip der überschreibenden Methoden 17 4.6 Neue Klassedatei erzeugen 18 4.7 Operator-Overloading 20 4.8 Interface 20 4.9 OOP-Beispiele 24

4.9.1 Beispiel punkt-linie 24 4.9.2 Koerper 25

4.10 weitere Tipps für Felder 27 5 Grunddialoge.................................................................................................................................. 29

5.1 MessageBox 29 5.1.1 Gesamtüberblick MessageBox.Show 30

6 Eigenschaften der GUI-Elemente .................................................................................................. 33 6.1 Form 33 6.2 Label 34 6.3 Button 34 6.4 TextBox, Editzeile 34 6.5 GroupBox 35 6.6 RadioButton 35 6.7 ListBox 36 6.8 ComboBox 37 6.9 ProgressBar 37 6.10 Menüs 38 6.11 SplitContainer 38

7 FileDialoge..................................................................................................................................... 40 7.1 OpenDialog 40 7.2 SaveFileDialog 40

8 Kommandoparameter..................................................................................................................... 41 8.1 Installationspfad 41

Page 3: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 3

9 Grafik ............................................................................................................................................. 42 9.1 Draw-Geometrie-Methoden 42

9.1.1 DrawArc 42 9.1.2 DrawBezier 43 9.1.3 DrawBeziers 45 9.1.4 DrawClosedCurve 46 9.1.5 DrawCurve Method 50 9.1.6 DrawEllipse 52 9.1.7 DrawLine 53 9.1.8 DrawLines 54 9.1.9 DrawPath 54 9.1.10 DrawPie 55 9.1.11 DrawPolygon 57 9.1.12 DrawRectangle 58

9.2 DrawString-Methoden 59 9.2.1 DrawString 59 9.2.2 DrawString(String, Font, Brush, PointF, StringFormat) 60

9.3 Fill-Methoden 61 9.3.1 FillClosedCurve 61 9.3.2 FillEllipse 62 9.3.3 FillPath 63 9.3.4 FillPie 64 9.3.5 FillPolygon 66 9.3.6 FillRectangle 67 9.3.7 FillRegion 68

9.4 DrawImage 69 9.4.1 DrawImage 69

9.5 Brush 72 9.5.1 SolidBrush 72 9.5.2 HatchBrush 72 9.5.3 LinearGradientBrush 74

9.6 Font 75 10 Indexverzeichnis......................................................................................................................... 76

Page 4: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 4

Abbildungsverzeichnis Abbildung 1 Erstellen des ersten Beispiels 7 Abbildung 2 Neue Klasse erzeugen 18 Abbildung 3 Neue Eintrag: New Item 19 Abbildung 4 Neue externe Klasse 19 Abbildung 5 Beispiel mit DrawPolygon 58

Page 5: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 5

1 Einführung in .net und C# Dieses Script bietet einen Einstieg in die Benutzung von Visual Studio. Es soll kein Lehrbuch ersetzen. Der Entwickler ist Andreas Heilsberg, er zuvor Turbo Pascal und Delphi mit entwickelt hat. Er wechselte nach dem Erfolg von Java zu Mircosoft. Er sollte ein Programmpaket .net / C# mit folgenden Eigenschaften entwickeln:

1.1 Überblick

1.1.1 C#

• C# ist das Äquivalent zu Java, aber auch eine Weiterentwicklung der Sprache C/C++ • Es gibt keine Pointer, (".", "::" und "->") werden nun komplett durch den Punkt ersetzt • Plattformunabhängig, eher im Sinne MS Desktop, MS PDA, MS Web

1.1.2 .net

• Common language runtime (CLR), Garbage Collection • Common language subset (CLS), gemeinsame Sprachbasis. • Es kann jede Sprache verwendet werden. Standardvokabular (Menge von Befehlen) • Microsoft intermediate language (MSIL), Zwischensprache • Just in Time Compiler (JIT) • Windows Forms (Swing) • ASP.net (Web Services) • ADO.net (Datenbanken) • XML, SOAP, UDDI (Kommunikation zw. den Komponenten

1.2 Eigenschaften

• Philosophie weitgehend identisch • Drag & Drop der GUI • Propertyfenster mit Property-Methoden kein normales get/set

public double x { set { m_x = value; } get { return m_x; } }

• Plattform unabhängigkeit • Sprache C# und viele andere • Umwandlung in Common Type System (CTS)

Page 6: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 6

• Aktuell Framework 3,5 • Common Language Runtime (CLR) • Unterschied zu Java: es erfolgt einer Übersetzung, kein Intepreter, übersetzt wird VOR oder

während des Programmslaufs • Unterstützt viele Programmiersprachen( C#, VB, Delphi, C++) • Umwandlung in einem Zwischencode • Sehr viele GUI-Elemente, bis zu Listview / Grid • Datenbank-Anbindung • Umfang bis zum Web-Server • Anweisungen sind weitgehend identisch zu Java / C++ • keine Header-Dateien • statt implement verwendet man using • Mehr Datentypen (unsigned) • Arrays mittels Blockstruktur, anders als in Java

Page 7: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 7

2 Beispiele

2.1 Hello World using System; namespace bsp1 { public class Programm { public static void Main(string[] args) { Console.WriteLine("Hello {0} im Jahr {1}", "ix", 2008); Console.ReadLine(); } // Main }// Programm } // bsp1 Die Anweisung „using“ bezieht sich auf die verwendeten Klassen. Hier kann man Tipparbeit sparen. Statt System.Console.WriteLine schreibt man dann einfacher Console.WriteLine. Mit dem Begriff „namespace“ kann man eigene „Pakete“ definieren. Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels

• File New Project • Visual C# • Console Application

Abbildung 1 Erstellen des ersten Beispiels

Die Taste „F5“ startet das Programm.

Page 8: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 8

3 Syntax

3.1 Datentypen in C# Der wichtigste Unterschied zu Java sind die vorzeichenlosen Datentypen byte, ushort, uint und ulong. Datentyp Beschreibung Wertebereich byte vorzeichenlos 0 bis 255 sbyte vorzeichenbehaftet -128 bis +127 short vorzeichenbehaftet -32768 bis +32767 ushort vorzeichenlos 0 bis 65535 int vorzeichenbehaftet -2.147.483.648 bis + 2.147.483.648 uint vorzeichenlos 0 bis 4.294,967,295 long vorzeichenbehaftet -263 bis 263-1 ulong vorzeichenlos 0 bis bis 264-1 single 32 Bit Gleitkommazahl, 7

Stellen -3,4·1038 bis -1,4·1045 für negative Werte 1,4·1045 bis 3,41038 für positive Werte

double 64 Bit Gleitkommazahl, 16 Stellen bool boolscher Wert true/false char Zeichen Uni-Codezeichen, 2 Byte decimal 96 Bit Dezimalwert String readonly Zeichenfolge Object Hauptklasse aller Objekte

3.2 String-Befehle Methode Beschreibung Length Länge eines Strings Clone Liefert Verweis des Strings. Sonst werden String als Referenz

„kopiert“ Compare Vergleicht zwei String. Der Rückgabewert ist true bei Gleichheit, sonst

false CompareTo Vergleicht zwei String ( -1, 0, +1) Concat Verbindet zwei Strings Copy Kopieren des Strings CopyTo Kopieren von Zeichen EndsWidth Vergleich mit Ende des String (\) Equals Haben zwei String denselben Inhalt. Die Adresse kann ja

unterschiedlich sein. Format Ähnlich der Printf-Anweisung, statt %d werden Nummer vergeben {0} GetEnumerator Funktion mit Parameter des String Durchlaufen des String IndexOf Sucht das erste Vorkommen IndexOfAny Liefert alle Vorkommen in einer Liste. Ähnlich der split-Anweisung in

PHP Insert Zeichen einfügen Join Die Methode fügt zwischen je zwei Elementen eines Strings-Arrays

Page 9: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 9

Methode Beschreibung einen angegebenen trennenden Strings ein und liefert das Ergebnis a,b,c ⇒ a_b_c

LastIndexOf Sucht das letzte Vorkommen LastIndexOfAny Liefert alle Vorkommen in einer Liste. Es gibt es umgekehrte

Reihenfolge PadLeft Rechtsbündige Ausrichtung, Die Leerstellen sind links PadRight Linksbündige Ausrichtung, Die Leerstellen rechts Remove Löschen von Zeichen Replace Ersetzen von Zeichen Split Aufteilen (Parsen oder \) StartsWith Prüft die ersten Zeichen auf Übereinstimmung SubString Liefert einen Teilstring ToCharArray Umwandlung von String in Char-Array ToLower Ergebnis alles in Kleinbuchstaben ToUpper Ergebnis alles in Großbuchstaben Trim Löschen von Leerzeichen am Anfang und am Ende TrimEnd Löschen von Leerzeichen am Ende TrimStart Löschen von Leerzeichen am Anfang

3.3 C# Sprache Die Sprache ist weitgehend identisch mit Java identisch, einige Konstrukte weichen aber von java bzw. C++ ab. In der normalen Syntax, Zuweisungen, if-Bedingung und Schleifen mit Java identisch.

3.3.1 Switch-case Unterschiedlich ist aber ist Switch-case-Anweisung Das untere Listing liefert eine Fehlermeldung, da zwischen den Case-Anweisung die break´s fehlen. switch (i) { case 0: erg = a + b; case 1: erg = a - b; case 2: erg = a * b; } Das untere Listing ist fehlerfrei. Leere Case-Anweisungen können verbunden werden. switch (i) { case 0: case 1: erg = a - b; // korrekt ohne Anweisung case 2: erg = a * b; }

Page 10: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 10

3.4 foreach Die zweite Variante der For-Schleife, ist die For-each-Schleife. Diese ist aus diversen anderen Programmiersprachen bekannt (Avenue, D, Java ab JDK 1.5). Beispiel: int [] array = { 1,2,3,4,5 }; foreach (int i in array) { Console.WriteLine(i); }

3.5 Enumerationen Verwendet man eine Auflistung, kann man diverse Konstanten definieren oder man benutzt eine Enumerationen, mit der die Konstanten mit ganzzahligem Wert automatisch definiert werden. Beispiel enum FB { AI, VW, W } Normalerweise werden die Konstanten von Null hochgezählt. Der Vorteil ist, wenn man einen Fachbereich hinzufügt. Der komplette Sourcecode bleibt korrekt. enum FB { AI=0x0000FF, VW=0xFF0000, W=0x00FF00 } Wie die Enumerationen ausgewertet wird, zeigt das untere Beispiel: // Definition enum FB { AI, VW, W } // Deklaration FB f; // Deklaration eines FB // Anweisungen f = FB.AI; // Zuweisung int i = (int)f; // Zuwesiung an ein int i = (int)FB.W;

Page 11: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 11

// Ausgabe void testfor() { foreach (int j in Enum.GetValues(typeof(FB))) { Console.WriteLine("FB: {0} {1}",Enum.GetName(type of(FB),j),j); } } // Ausgabe Ergebnis der Ausgabe: Fachbereich AI 0 Fachbereich VW 1 Fachbereich W 2 Problem: // Diese Verteilung hat Lücken, in einer For-Schleife gibt es dann Probleme, siehe unten enum FB { AI=1, VW=3, W=5 } // Diese For-SAchleife funktioniert nicht richtig for (int k = (int)FB.AI; k <= (int)FB.W; k++) { Console.WriteLine("FB {0} {1}", Enum.GetName(typ eof(FB), k), k); } Console.WriteLine(); // bessere Variante foreach (int j in Enum.GetValues(typeof(FB))) { Console.WriteLine("FB {0} {1}", Enum.GetName(typ eof(FB), j), j); } Abhilfe schafft folgende Funktionen. Diese testet ob FB.IsDefined(typeof(FB),i) for (int k = (int)FB.AI; k <= (int)FB.W; k++) { if ( FB.IsDefined(typeof(FB),k) ) Console.WriteLine("FB {0} {1}", Enum.GetName(ty peof(FB), k), k); }

Page 12: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 12

3.6 Ausgabe in der Console Zur Ausgabe dient die Funktion „Console.WriteString“. Der erste Parameter bezieht sich auf den Text mit den Platzhaltern für die Variablen. Beispiel: Console.WriteLine("d: {0}", d); Console.Write("d: {0}", d);

3.7 Eingabe von der Console Zur Eingabe dient die Funktion „Console.ReadString“. Der erste Parameter bezieht sich auf den Text mit den Platzhaltern für die Variablen. Beispiel: Console.WriteLine("d: {0}", d);

3.7.1 Formatierte Ausgaben Folgende Platzhalter definieren eine formatierte Ausgaben:

• # beliebige Zahl oder Leerzeichen • 0 beliebige Zahl oder eine Null

Es muss immer ein Dezimalpunkt eingegeben werden. double d = 1.0 / 3.0; // 0 0 oder zahl besser ###0.00 als ###.## Console.WriteLine("d: {0:##0.00}", d); Format-Code Beschreibung {0} Zahl mit mehreren Nachkommastellen {0:##0.00} Mit zwei Nachkommastellen

Dezimaltrennzeichen ist ein Punkt {0:p2} Mit zwei Nachkommastellen

Dezimaltrennzeichen ist ein Komma {0,7:c} Ausrichtung ( "" ).PadRight(24, '-' ) Ergibt 24 waagerechte Striche ( "123" ).PadRight(24, '-' ) Ergibt die Zahl 123 und danach 24 waagerechte

Striche ( "123" ).PadLeft(10, 'x' ) Insgesamt 10 Zeichen. Linksbündig werden „x“

eingetragen. Ergebnis: „xxxxxxx123“

Page 13: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 13

3.8 Parameter-Übergabe C# kennt 4 Parameter-Übergabe-Typen

• Parameter per Value, eine Kopie wird übergeben • Parameter per Referenz (ref), kann gelesen und gesetzt werden • Parameter für die Ausgabe (out), kann nur gesetzt werden • Parameter für Arrays (params), immer am Ende der Liste,

Wichtig, die Typen müssen AUCH in der Aufrufliste stehen. Beispiele: // Funktion mit einem Out-Parameter // erg darf nicht vor dem Setzen gelesen werden static void add2(int a, int b, out int erg) { erg = a + b; } // Funktion mit einem Out-Parameter // b darf gelesen und gesetzt werden static void add3(int a, ref int b) { b = a + b; } // dieses Beispiel zeigt die Verarbeitung von Param etern // static void ShowNumbers (params int[] numbers) { foreach (int x in numbers) { Console.Write (x+" "); } Console.WriteLine(); } main() { int a,b, c; a = 11; b = 22; add2(a, b, out c); // out signalisiert Ausgabeparameter Console.WriteLine("Erg1: a {0} b {1} c{2}", a, b, c); a = 11; b = 22; add3(a, ref b); // ref signalisiert Referenzparameter Console.WriteLine("Erg2: a {0} b {1}", a, b); .. int[] x = {1, 2, 3}; ShowNumbers (x); ShowNumbers (4, 5); ShowNumbers (4, 5, 6, 7); } // bsp3

Page 14: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 14

Ergebnis: Erg1: a 11 b 22 c33 Erg2: a 11 b 33 1 2 3 4 5 4 5 6 7

3.9 Delegates Delegates sind der Ersatz für Pointerfunktionen. Delegates können sowohl statische als auch Instanzmethoden referenzieren. Sie müssen aber denselben Rückgabewert und dieselben Parametertypen besitzen wie die zu referenzierenden Methoden. Prinzip: 1) Deklaration der delegate-Protyp-Funktion public delegate int Del_methode(int val); 2) Definition einer speziellen delegate-Funktion public static int Addint(int a, int b) { return a + b; } public static int Multint(int a, int b) { return a * b; } Die obigen Anweisungen definieren zwei „Funktionspointer“. Damit erreicht man eine hohe Flexibilität bezüglich der Funktionalität. Man kann Funktionen schreiben, die eine Funktion übergeben bekommen, und so weitgehend unabhängig programmiert werden können (Framework). 3) Zuweisung und Aufruf int a,b; a=1; b=2; Del_methode calc1 = new Del_methode(Addint); Del_methode calc2 = new Del_methode(Multint); c = calc1(a, b); c = calc2(a, b); Ein Delegate erzeugt man wie eine Instanz einer Klasse. Als Parameter erwartet sie eine Methode.

Page 15: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 15

3.10 Try Catch

Die Exception ist fast identisch mit Java bzw. C++ Beispiele: // Konvertierung eines Strings in einem Integer-Wert try { Int32 iValue = Convert.ToInt32(sValue); } catch (Exception me) { Console.WriteLine(me.ToString() ); } public double calc(double d) { try { double j = sqrt(d); } catch (MyException me) { Console.WriteLine(me.m_msg); } catch { /* alle restlichen Exceptions */ } finally { /* Aufraeumen */ } } // calc

Page 16: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 16

4 Objektorientierte Programmierung Dieses Kapitel zeigt die Unterschiede zwischen den Java, C++ und C# beim Objektorientierten programmieren. Es wird vorrausgesetzt, dass man Grundkenntnisse besitzt. Die Definition der Klasse ist ein Mix ein Java und C++. Der Zugrif auf die Member-Variablen erfolgt durch vier Stufen

• private • internal // nur in Assembly, Packages • public • protected // Zugriff nur in abgeleiteten Klassen

Modifizierer Innerhalb der

Klasse Innerhalb der Ableitungen

Außerhalb der Klasse

Außerhalb der Anwendung

public Ja Ja Ja Ja internal Ja Ja Ja Nein protected Ja Ja Nein Nein private ja Nein Nein Nein

4.1 Konstruktor Der Konstruktor ist ganz normal wie in Java oder C++. Der Unterschied tritt erst bei Vererbungen zu Tage. Hier wird „base“ und „this“ verwendet. Mit base wird der Konstruktor der oberen Klasse aufgerufen. Die Position stammt aus C++, statt base verwendet Java super. Die statische Erzeugung eines Objektes à la C++ ist nicxht möglich. Man muss immer den new-Operator benutzen.

4.2 Dekonstruktor Der Dekonstruktor ist ähnlich wie in Java. ~student() { }

4.3 sealed Mit dem Zusatz „sealed“ kann man verhindern, das man von der aktuellen Klasse ableiten kann. Dies kann ja sinnvoll sein, wenn man Zugriff auf private Variablen haben möchte. Beispiel:

Page 17: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 17

sealed class klasse1 { … } // klasse1

4.4 Set-Get-Methoden Die set- und get-Methoden werden eher im Delphi-Stil programmiert. Man definiert die variable und beschreibt dann die Methoden: private int m_Matrnr ; public int Matrnr { get { return m_Matrnr; } set { if ( value>0 && value < 99999 ) m_Matrnr=value; } } // int Matrnr Die Variable ist vor einem Zugriff geschützt. Man definiert nach der Deklaration die Methode, die aber im Code wie eine normale Variable aussieht. Der Compiler verarbeitet den Zugriff auf die get/set-Methoden. Für das obige Beispiel wäre dann folgender Code möglich: public void test { int k; student std = new student (); std.Matrnr=17421; // ruft die set-Methode auf k = std.Matrnr; // ruft die get-Methode auf }

4.5 Überschriebene Methoden Dieses Kapitel zeigt die Besonderheiten bezüglich Methoden, die vererbt bzw. überschrieben werden sollen. In Java können die Methoden einfach überschrieben werden. In C++ muss man das Prefix „virtual“ in der Basis-Klasse benutzen. In C# muss man beide Methoden mit einem Prefix versehen. In der Oberklasse das Prefix „virtual“, in der abgeleiteten Klasse das Prefix „override“.

4.5.1 Prinzip der überschreibenden Methoden class Pflanze { virtual public void print()

Page 18: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 18

{ Console.WriteLine("in Pflanze"); } } class Blume : Pflanze { override public void print() { Console.WriteLine("in Bume"); } }

4.6 Neue Klassedatei erzeugen Mit rechter Maustaste auf dem Projektnamen in linken Baum gehen.

Abbildung 2 Neue Klasse erzeugen

Im Popupmenü wählt man erst den Eintrag „Add“ und dann „New Item…“ aus.

Page 19: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 19

Abbildung 3 Neue Eintrag: New Item

Abbildung 4 Neue externe Klasse

Rumpf der neuen Klasse: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OOP2a { class Koerper2 { } }

Page 20: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 20

4.7 Operator-Overloading In Java ist dieses noch nicht erlaubt, in C++ ist dieses eine gängige Eigenschaft. Syntax: public static Klasse operator +(Klasse k1, Klasse k2) { Klasse temp = new Koerper(); temp.member = k1.member + k2.member; return temp; } Folgende Operatoren können überladen werden: Operatoren Overloadbar +, -, *, /, %, &, |, <<, >> Alle binären Operatoren können überladen werden +, -, !, ~, ++, --, true, false Alle unären Operatoren können überladen werden ==, !=, <, >, <= , >= Alle relationalen Operatoren können, paarweise, überladen

werden &&, || Keine Überladung () Cast-Operator +=, -=, *=, /=, %= Können überladen werden. Funktioniert aber automatisch =, . , ?:, ->, new, is, as, sizeof Keine Überladung

4.8 Interface Interfaces, die im Deutschen auch oft als Schnittstellen bezeichnet werden, haben eine ähnliche Aufgabe wie abstrakte Klassen. Sie implementieren weder Datenelemente noch ausführbaren Code, sondern lediglich Deklarationen von Methoden. Ein Interface kann nicht als Instanz erzeugt werden, sondern nur von Klassen, die dieses Interface implementieren. Interfaces können auch hierarchisch aufgebaut sein. Der Unterschied zu einer abstrakten Klasse ist, dass eine Klasse lediglich eine Basisklasse haben kann, aber beliebig viele Interfaces implementieren kann. Interfaces können also als Ersatz zur zur Mehrfachvererbung dienen. Falls eine Klasse neben einer Basisklasse noch von mindestens einem Interface abgeleitet ist, so muss bei der Klassendeklaration die Basisklasse vor den Interfaces angegeben werden: class klasse1: overklasse, interface1 Die Syntax eines Interfaces unterscheidet sich von der einer abstrakten Klasse nur dadurch, dass das Schlüsselwort class durch interface ersetzt ist und das Schlüsselwort abstract entfällt, da Interfaces per Definition abstrakt sind. Wichtig: Eine Subklasse erbt die Methoden von der Oberklasse. Das ist der Vorteil der Vererbung. Bei komplexen Klassen bzw. bei mehreren Klassenfamilien, ist es sinnvoller, die Schnittmenge möglichst klein zu halten. Eine Klasse, die eine Schnittstelle implementiert, verpflichtet diese neu zu imple-mentieren, also keine Vererbung. Eine Funktion, die ein Objekt einer Klasse mit einer Schnittstelle hat, weiß nun, dass man diese Funktion aufrufen kann.

Page 21: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 21

Syntax: interface IInterface1 { void print(); } class Klasse1 : IInterface1 { void print() { } } public void test() { Klasse1 kl1 = new Klasse1(); kl1.print(); // Aufruf einer Schnittstellenmethod e } Der Vorteil der Verwendung von Schnittstellen gegenüber einer Klasse, ist die Unabhängigkeit im Klassenbaum. Keine Methode, keine Klasse muss angepasst werden. Der Nachteil ist der erhöhte Aufwand, alle Methoden in jedem Klassenbaum zu implementieren. In Java ist es möglich, ein Array mit Interfaces zu erzeugen. In C# kann man dieses nur mit der Deklaration erreichen. Alternative dazu ist eine ArrayList. Damit kann man beliebige „Objekte“ in einem Array speichern (siehe Beispiel unten). Das Beispiel definiert eine Interface, IPrint und diverse Klassen. Dabei sind einige als Klassenbaum implementiert. In der main-Methode werden diese unterschiedlichen Klassen in einem „Interface“-Array gespeichert und dann wird in einer For-Schleife bzw. in einer foreach-Schleife die print-Methode aufgerufen. In diesen Schleifen ist nicht bekannt, aus welcher Klasse das Objekt kommt. Quellcode: // Interface Deklaration interface IPrint { void print(); } // 1. Klasse, die die Schnittstelle implementiert class bsp1 : IPrint { string m_name; public bsp1(string name) { this.m_name = name; } public void print() { Console.WriteLine("Name bsp1: {0}", m_name );

Page 22: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 22

} } // 2. Klasse, die die Schnittstelle implementier t class bsp2 : IPrint { string m_name; public bsp2(string name) { this.m_name = name; } public void print() { Console.WriteLine("Name bsp2: {0}", m_nam e); } } // 3. Klasse, die die Schnittstelle implementiert // Diese Klasse ist Oberklasse class fahrzeug : IPrint { protected int ps; public fahrzeug(int ps) { this.ps = ps; } // hier wichtig das virtual virtual public void print() { Console.WriteLine("Fahrzeug PS: {0}", ps) ; } } // fahrzeug // 4. Klasse, die die Schnittstelle implementiert // Schnittstelle mittels Vererbung ! class pkw : fahrzeug { string farbe; public pkw(int ps, string farbe) : base(ps) { this.farbe = farbe; } override public void print() { Console.WriteLine("PKW: Ps: {0} farbe: {1}", ps, farbe); } } // pkw

Page 23: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 23

// 5. Klasse, die die Schnittstelle implementiert // Schnittstelle mittels Vererbung ! class lkw : fahrzeug { int volumen; public lkw(int ps, int volumen) : base(ps) { this.volumen = volumen; } override public void print() { Console.WriteLine("LKW: Ps: {0} vol: {1} ", ps, volumen); } } // lkw // 6. Klasse, die die Schnittstelle implementiert class schiff : IPrint { int passagiere; public void print() { Console.WriteLine("Schiff: passagiere: {0} ", passagiere); } public schiff(int passagiere) { this.passagiere = passagiere; } } // schiff class Program { static void Main(string[] args) { bsp1 b1; bsp2 b2; b1 = new bsp1("bsp1"); b2 = new bsp2("bsp2"); fahrzeug f1 = new fahrzeug(122); fahrzeug f2 = new fahrzeug(132); fahrzeug f3 = new fahrzeug(142); fahrzeug f4 = new fahrzeug(125); pkw p1 = new pkw(12, "rot"); pkw p2 = new pkw(122, "blau"); schiff s1 = new schiff(12345); s1.print(); // Diese Zuwesiung funktioniert IPrint[] schl = { b1, f1, f2, f3, f4, p1, p 2, b2 }; for (int i = 0; i < 7; i++)

Page 24: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 24

{ schl[i].print(); } Console.WriteLine(); // using System.Collections ArrayList schl2 = new ArrayList(); schl2.Add(b1); schl2.Add(f1); schl2.Add(f2); schl2.Add(f3); schl2.Add(f4); schl2.Add(p1); schl2.Add(p2); schl2.Add(b2); // Nun die Ausgabe foreach (IPrint item in schl2) { item.print(); } Console.ReadLine(); } } }

4.9 OOP-Beispiele

4.9.1 Beispiel punkt-linie class punkt { protected int m_x, m_y; public punkt(int x, int y) { this.m_x = x; this.m_y = y; } } class linie : punkt { private int m_strichdicke; public linie(int strichdicke): this(strichdicke,0,0) { m_strichdicke = strichdicke; } public linie(int strichdicke, int x, int y): base(y,x) { m_strichdicke = strichdicke;

Page 25: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 25

} } static void Main(string[] args) { punkt p1; linie l1, l2; p1 = new punkt(1, 2); l1 = new linie(22,3,4); l2 = new linie(11); } Dieses Beispiel zeigt alle Varianten, die man im OOP benötigt. Mit „this(…)“ wird ein anderer Konstruktor aufgerufen. Mit „base“ wird die Oberklasse

4.9.2 Koerper Dieses Beispiel zeigt den vollständigen Quellcode einer Vererbung mit Operator-Overlaoding. Die Klasse Koerper ist die Grundklasse. Hier wird die Variable m_volumen deklariert. Außerdem ist in dieser Klasse die Methode „print“, die in den weiteren Ableitungen „überschrieben“ werden soll. Dazu muss das Prefix „virtual“ benutzt werden. In Koerper sind zwei Konstruktoren definiert. Dabei ist es guter Stil, nur einen echten Konstruktor zu benutzen. Dazu ruft man den zweiten einfach mit this auf. Die Klasse Koerper2 überschreibt die print-Methode, während „Koerper3“ die normale Methode übernimmt. Den Konstruktor der Oberklasse erreicht man mit „base“. Auch hier sollte man zwischen this und base trennen, siehe Quellcode. Für die Klasse Koerper wurde noch der Plus-Operator überladen. Hier werden einfach zwei Volumen addiert. Hinweis: Die Methode + ist nur für die Klasse Korper definiert. Genauer, die linke Seite darf nur vom Typ Koerper sein. Die rechte Seite kann Typen der Klassen (Koerper, Koerper2 und Koerper3) haben. using System; using System.Text; namespace OOP2 { class Koerper { private int m_volume; public Koerper() : this(0) { //m_volume = 0; } public Koerper(int volume) { m_volume = volume; } public int volume

Page 26: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 26

{ get { return m_volume; } set { if (value > 0 && value < 99999) m_vol ume = value; } } virtual public void print() // für Ableitung { Console.WriteLine("Koerper "+m_volume); } // Operator overloading public static Koerper operator + (Koerper k1, Koerper k2) { Koerper temp = new Koerper(); temp.volume = k1.volume + k2.volume; return temp; } } // Koerper class Koerper2 : Koerper { private string m_name; public Koerper2 (int volume):this("noname",volume) { m_name = name; } public Koerper2(string name, int volume):base(volum e) { m_name = name; } public string name { get { return m_name; } } override public void print() { Console.WriteLine( "Koerper2 Name: {0} Volumen {1}", m_n ame, volume); } } // Koerper2 class Koerper3 : Koerper { private string m_name; public Koerper3(string name, int volume): bas e(volume)

Page 27: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 27

{ m_name = name; } public string name { get { return m_name; } } } // Koerper3 class Program { static void Main(string[] args) { Koerper kugel, ziegel, kegel; // keine Erz eugung, kein C++ kugel = new Koerper(); kugel.volume = 14721; kugel.print(); ziegel = new Koerper(12345); ziegel.print(); Console.WriteLine("Operator Overlaoding!"); kegel = kugel + ziegel; kegel.print(); Console.WriteLine(); Koerper2 kugel2, ziegel2; // keine Erzeugu ng, kein C++ Koerper3 kugel3; // keine Erzeugung, kein C++ kugel2 = new Koerper2("kugel",14721); kugel2.print(); ziegel2 = new Koerper2("ziegel",12345); ziegel2.print(); kugel3 = new Koerper3("kugel",14721); kugel3.print(); Console.ReadLine(); } } }

4.10 weitere Tipps für Felder string [] names = { "Herbert", "Gerhard", "Angela"}; Regelmäßige mehrdimensionale Felder werden mit folgender Notation vereinbart: double [,] matrix = new double [2,3]; Unregelmäßige, mehrdimensionale Felder (jagged arrays) schließlich definiert man in C# wie folgt: double [][] jagged_matrix = new double[2][];

Page 28: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 28

jagged_matrix[0] = new double[3]; // der erste Vektor hat 3 Elemente jagged_matrix[1] = new double[5]: // der zweite Vektor hingegen 5 Mittels Methoden wie GetLength oder Eigenschaften wie Rank lassen sich wichtige Informationen von Feldern abrufen, beispielsweise ihre Länge und Dimension.

Page 29: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 29

5 Grunddialoge

5.1 MessageBox 1) MessageBox.Show("text"); 2) MessageBox.Show("text\n2. Zeile", "Caption"); 3) MessageBox.Show("text\n2. Zeile", "Caption", MessageBoxButtons.Buttonsauswahl); Optionen:

• MessageBoxButtons.AbortRetryIgnore • MessageBoxButtons.OK • MessageBoxButtons.OKCancel • MessageBoxButtons.RetryCancel • MessageBoxButtons.YesNo • MessageBoxButtons.YesNoCancel

3) MessageBox.Show("text", "Caption", MessageBoxButtons, MessageBoxIcon) Displays a message box with the specified text, caption, buttons, icon, and default button. 4) MessageBox.Show("text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton) : MessageBoxIcon

• Optionen für • Asterisk • Error • Exclamation • Hand • Information • None • Question • Stop • Warning

:MessageBoxDefaultButton MessageBoxDefaultButton:

• Button1 • Button2 • Button3

Page 30: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 30

Beispiele: result = MessageBox.Show( "Text", "Caption", MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk); result = MessageBox.Show( "Text", "Caption", MessageBoxButtons. YesNoCancel, MessageBoxIcon. Question, MessageBoxDefaultButton.Button2); 5) MessageBox.Show("text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions) MessageBoxOptions:

• DefaultDesktopOnly • RightAlign // Ausrichtung des Textes rechts • RtlReading • ServiceNotication

MessageBox.Show( "Text", "Caption", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification);

5.1.1 Gesamtüberblick MessageBox.Show :Gesamtüberblick Name Beschreibung MessageBox.Show ("Text") Zeigt ein Meldungsfeld mit angegebenem Text an. Wird

von .NET Compact Framework unterstützt. MessageBox.Show (IWin32Window, "Text")

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text an.

MessageBox.Show ( "Text ", "Caption")

Zeigt ein Meldungsfeld mit dem angegebenen Text und der angegebenen Beschriftung an. Wird von .NET Compact Framework unterstützt.

MessageBox.Show (IWin32Window, "Text", "Caption")

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text und der angegebenen Beschriftung an.

MessageBox.Show ("Text", "Caption" , MessageBoxButtons)

Zeigt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung und den angegebenen Schaltflächen an.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons)

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung und den angegebenen Schaltflächen an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon)

Zeigt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen und dem angegebenen Symbol an.

Page 31: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 31

Name Beschreibung MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon)

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen und dem angegebenen Symbol an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton)

Zeigt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, dem angegebenen Symbol und der Standardschaltfläche an. Wird von .NET Compact Framework unterstützt.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton)

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol und der Standardschaltfläche an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions)

Zeigt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, dem angegebenen Symbol, der Standardschaltfläche und Optionen an. Ausrichtung des Textes

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions)

Zeigt vor dem angegebenen Objekt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der Standardschaltfläche und Optionen an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, Boolean)

Zeigt ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String)

Zeigt unter Verwendung der angegebenen Hilfedatei ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String)

Zeigt unter Verwendung der angegebenen Hilfedatei ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String, HelpNavigator)

Zeigt mithilfe der angegebenen Hilfedatei und HelpNavigator ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons,

Zeigt mithilfe der angegebenen Hilfedatei und des angegebenen Hilfeschlüsselworts ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung,

Page 32: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 32

Name Beschreibung MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, „Text“, „Caption“)

den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String, HelpNavigator)

Zeigt mithilfe der angegebenen Hilfedatei und HelpNavigator ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, „Text“, „Caption“)

Zeigt mithilfe der angegebenen Hilfedatei und des angegebenen Hilfeschlüsselworts ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show ( "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String, HelpNavigator, Object)

Zeigt mithilfe der angegebenen Hilfedatei, HelpNavigator und des angegebenen Hilfethemas ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

MessageBox.Show (IWin32Window, "Text", "Caption", MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions, String, HelpNavigator, Object)

Zeigt mithilfe der angegebenen Hilfedatei, HelpNavigator und des angegebenen Hilfethemas ein Meldungsfeld mit dem angegebenen Text, der angegebenen Beschriftung, den angegebenen Schaltflächen, dem angegebenen Symbol, der angegebenen Standardschaltfläche, den angegebenen Optionen und der Schaltfläche Hilfe an.

Quelle: http://msdn.microsoft.com/de-de/library/system.windows.forms.messagebox.show(VS.80).aspx

Page 33: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 33

6 Eigenschaften der GUI-Elemente

6.1 Form • Name • AutoScroll False/True • AutoSize False/True • AutoSizeMode: GrowOnly, GrowAndShrink • BackColor • BackGroundImage • • CancelButton • MaximizeBox • MinimizeBox

• Cursor • DoubleBuffered • Enabled • Font • ForeColor • FormBoderStyle:

o None o FixedSingle o Fixed3D o FixedDialog o Sizable o FixedToolWindow o SizableToolWindow

• Icon • IsMDIContainer • KeyPreview • Location • Locked • MainMenuStrip • Opacity • ShowIcon • Size • StartPosition:

o Manual o CenterScreen o WindowsDefaultLocation o WindowsDefaultBounds o CenterParent

• Tag • Text: (Caption) • TopMost False/True (Top of the Stay, Toolfenster) • WindowState: Normal, Minimized, Maximized

(System.Windows.Forms.FormWindowState.Minimized)

Page 34: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 34

6.2 Label

• Name • Anchor Top/Left • BackColor • BorderStyle • Cursor • Enabled False/True • Font • ForeColor • Image • ImageAlign • Location: x y • Locked True False • Margin • Size: Width Height • TabIndex • TabStop • Tag • Text: Beschriftung • TextAlign: 9 Varianten • Visible

6.3 Button

• Name • Anchor Top/Left • AutoSize: True/False • BackColor • Cursor • DialogResult: Ok Cancel Abort Retry Ignore Yes No • Enabled False/True • Font • ForeColor • Location: x y • Locked True False • Size: Width Height • TabIndex • TabStop • Tag • Text • TextAlign: 9 Varianten MidleCenter • Visible

6.4 TextBox, Editzeile

• Name • Anchor Top/Left • BackColor

Page 35: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 35

• Cursor • Enabled False/True • Font • ForeColor • Lines • Multiline False/true • Location: x y • Locked True False • PasswordChar • ReadOnly False/True • Size: Width Height • TabIndex • TabStop • Tag • Text: Inhalt • Visible • WordWrap False/True

6.5 GroupBox

• Name • Anchor Top/Left • BackColor • BorderStyle • Cursor • Enabled False/True • Font • ForeColor • Location: x y • Locked True False • Margin • Size: Width Height • TabIndex • TabStop • Tag • Text: Beschriftung • Visible

6.6 RadioButton

• Name • Anchor Top/Left • AutoCheck • BackColor • CheckAlign 9 Varianten • Checked • Cursor • DataBindings • Enabled False/True

Page 36: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 36

• Font • ForeColor • Image • ImageAlign • Location: x y • Locked True False • Margin • Size: Width Height • TabIndex • TabStop • Tag • Text: Beschriftung • TextAlign • Visible

6.7 ListBox

• Name • Anchor Top/Left • BackColor • Cursor • DataSource • Enabled False/True • Font • ForeColor • FormatString • FormattingEnabled • Items (Collection), Inhalt der Texte • Location: x y • Locked True False • Margin • MultiColumn • SelectionMode:

o None o One o MultiSimple o MultiExtended

• Size: Width Height • TabIndex • TabStop • Tag • UsesTabStop • Text: Beschriftung • TextAlign • ValueMember (DBS) • Visible

liste.Items.Clear(); liste.Items.add("eintrag1"); liste.Items.add("eintrag2"); liste.SelectedIndex = 0;

Page 37: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 37

6.8 ComboBox

• Name • Anchor Top/Left • BackColor • Cursor • DataSource • DrawMode normal, OwnerDrawFixed, OwnerDrawVariable • DropDownHeight • DropDownStyle:

o Simple Einfacher Editor o DrownDown ComboBox mit Editor o DrownDownList Nur ComboBox

• Enabled False/True • Font • ForeColor • FormatString • FormattingEnabled • ItemHeight • Items (Collection) • Location: x y • Locked True False • Margin • MaxDropDownItems • Size: Width Height • Sorted • TabIndex • TabStop • Tag • Text: Inhalt, bei Simple und Dropdown • TextAlign • Visible

cmb1.Items.Clear(); cmb1.Items.add("eintrag1"); cmb1.Items.add("eintrag2"); cmb1.SelectedIndex = 0;

6.9 ProgressBar Minimum: Minmaler Wert Maximum: Maximaler Wert Value: Aktueller Wert Style: Blocks // große Blöcke

Continuous // feine Striche Marquee // autom. laufender ProgressBar

Page 38: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 38

6.10 Menüs

• Name • Aligment • AutoSize • BackColor • BackgroundImage • Checked False/True • DisplayStyle: ImageAndText • DropDown • DropDownItems • Enabled • Font • ForeColor • Image • ImageAlign • ImageScaling • ShortCutKeys • Size • Tag • Text • TextAlign • TextDirection • ToolTipText • Visible

6.11 SplitContainer

• Name • Anchor: Top, Left (Fullsize) • BaclColor • BackgroundImage • BorderStyle • Enabled • FixedPanel • Font • ForeColor • IsSplitterFixed • Location • Orientation: Vertical / Horizontal • Panel1 • Panel2 • Panel1MinSize • Panel2MinSize • Size • SplitterDistance, Abstand vom linken Rand • SplitterIncrement • SplitterWidth

Page 39: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 39

• TabIndex • TabStop • Tag • Visible

Page 40: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 40

7 FileDialoge

7.1 OpenDialog OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "txt files (*.txt)|*.txt|pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2;// zählt von 1 ! openFileDialog1.DefaultExt = ".txt"; openFileDialog1.InitialDirectory="c:\\daten\\0"; openFileDialog1.Multiselect=true; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string[] sFiles; sFiles = openFileDialog1.FileNames; foreach (string sFile in sFiles) { MessageBox.Show(sFile, Application.ProductName); } } OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "txt files (*.txt)|*.txt|pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2;// zählt von 1 ! openFileDialog1.DefaultExt = ".txt"; openFileDialog1.InitialDirectory="c:\\daten\\0"; openFileDialog1.Multiselect=false; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string sFile = openFileDialog1.FileName.ToString(); MessageBox.Show(sFile, Application.ProductName); }

7.2 SaveFileDialog SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "txt files (*.txt)|*.txt|pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 1;// zählt von 1 ! saveFileDialog1.DefaultExt = ".txt"; saveFileDialog1.InitialDirectory = "c:\\daten"; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string sFile = saveFileDialog1.FileName.ToString(); MessageBox.Show(sFile, Application.ProductName); }

Page 41: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 41

8 Kommandoparameter // The Length property is used to obtain the length of the array. // Notice that Length is a read-only property: Console.WriteLine("Number of command line parameters = {0}", args.Length); for(int i = 0; i < args.Length; i++) { Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]); } oder Console.WriteLine("Number of command line parameters = {0}", args.Length); foreach(string s in args) { Console.WriteLine(s); }

8.1 Installationspfad Bestimmen des Installationspfads String sProgramm = Application.ExecutablePath; int ipos=sProgramm.LastIndexOf("\\"); String sPath = sProgramm.Substring(0, ipos+1);

Page 42: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 42

9 Grafik Quelle: http://msdn.microsoft.com/en-us/library/zy3kce13.aspx

9.1 Draw-Geometrie-Methoden

9.1.1 DrawArc public void DrawArc( Pen pen, Rectangle rect, float startAngle, float sweepAngle ) public void DrawArc( Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle ) public void DrawArc( Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the arc. rect Type: System.Drawing..::.Rectangle RectangleF structure that defines the boundaries of the ellipse. startAngle Type: System..::.Single Angle in degrees measured clockwise from the x-axis to the starting point of the arc. sweepAngle Type: System..::.Single

Page 43: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 43

Angle in degrees measured clockwise from the startAngle parameter to ending point of the arc. private void DrawArcRectangle(PaintEventArgs e) { // Create pen. Pen blackPen= new Pen(Color.Black, 3); // Create rectangle to bound ellipse. Rectangle rect = new Rectangle(0, 0, 100, 200); // Create start and sweep angles on ellipse. float startAngle = 45.0F; float sweepAngle = 270.0F; // Draw arc to screen. e.Graphics.DrawArc(blackPen, rect, startAngle, sweepAngle); }

9.1.2 DrawBezier public void DrawBezier( Pen pen, Point pt1, Point pt2, Point pt3, Point pt4 ) public void DrawBezier( Pen pen, PointF pt1, PointF pt2, PointF pt3, PointF pt4 ) Parameters pen Type: System.Drawing..::.Pen Pen structure that determines the color, width, and style of the curve. pt1 Type: System.Drawing..::.Point Point structure that represents the starting point of the curve. pt2 Type: System.Drawing..::.Point Point structure that represents the first control point for the curve. pt3 Type: System.Drawing..::.Point

Page 44: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 44

Point structure that represents the second control point for the curve. pt4 Type: System.Drawing..::.Point Point structure that represents the ending point of the curve. private void DrawBezierPoint(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create points for curve. Point start = new Point(100, 100); Point control1 = new Point(200, 10); Point control2 = new Point(350, 50); Point end = new Point(500, 100); // Draw arc to screen. e.Graphics.DrawBezier(blackPen, start, control1, control2, end); } public void DrawBezier( Pen pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4 ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the curve. x1 Type: System..::.Single The x-coordinate of the starting point of the curve. y1 Type: System..::.Single The y-coordinate of the starting point of the curve. x2 Type: System..::.Single The x-coordinate of the first control point of the curve.

Page 45: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 45

y2 Type: System..::.Single The y-coordinate of the first control point of the curve. x3 Type: System..::.Single The x-coordinate of the second control point of the curve. y3 Type: System..::.Single The y-coordinate of the second control point of the curve. x4 Type: System..::.Single The x-coordinate of the ending point of the curve. y4 Type: System..::.Single The y-coordinate of the ending point of the curve.

9.1.3 DrawBeziers public void DrawBeziers( Pen pen, Point[] points ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the curve. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that represent the points that determine the curve. private void DrawBeziersPoint(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create points for curve. Point start = new Point(100, 100); Point control1 = new Point(200, 10); Point control2 = new Point(350, 50); Point end1 = new Point(500, 100); Point control3 = new Point(600, 150); Point control4 = new Point(650, 250); Point end2 = new Point(500, 300); Point[] bezierPoints =

Page 46: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 46

{ start, control1, control2, end1, control3, control4, end2 }; // Draw arc to screen. e.Graphics.DrawBeziers(blackPen, bezierPoints); } public void DrawBeziers( Pen pen, PointF[] points ) private void DrawBeziersPointF(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create points for curve. PointF start = new PointF(100.0F, 100.0F); PointF control1 = new PointF(200.0F, 10.0F); PointF control2 = new PointF(350.0F, 50.0F); PointF end1 = new PointF(500.0F, 100.0F); PointF control3 = new PointF(600.0F, 150.0F); PointF control4 = new PointF(650.0F, 250.0F); PointF end2 = new PointF(500.0F, 300.0F); PointF[] bezierPoints = { start, control1, control2, end1, control3, control4, end2 }; // Draw arc to screen. e.Graphics.DrawBeziers(blackPen, bezierPoints); }

9.1.4 DrawClosedCurve public void DrawClosedCurve( Pen pen, Point[] points ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that define the spline.

Page 47: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 47

private void DrawClosedCurvePoint(PaintEventArgs e) { // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3); // Create points that define curve. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = { point1, point2, point3, point4, point5, point6, point7 }; // Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Draw closed curve to screen. e.Graphics.DrawClosedCurve(greenPen, curvePoints); } public void DrawClosedCurve( Pen pen, PointF[] points ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.PointF>[]()[] Array of PointF structures that define the spline. private void DrawClosedCurvePointF(PaintEventArgs e) { // Create pens.

Page 48: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 48

Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3); // Create points that define curve. PointF point1 = new PointF(50.0F, 50.0F); PointF point2 = new PointF(100.0F, 25.0F); PointF point3 = new PointF(200.0F, 5.0F); PointF point4 = new PointF(250.0F, 50.0F); PointF point5 = new PointF(300.0F, 100.0F); PointF point6 = new PointF(350.0F, 200.0F); PointF point7 = new PointF(250.0F, 250.0F); PointF[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Draw closed curve to screen. e.Graphics.DrawClosedCurve(greenPen, curvePoints); } public void DrawClosedCurve( Pen pen, Point[] points, float tension, FillMode fillmode ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that define the spline. tension Type: System..::.Single Value greater than or equal to 0.0F that specifies the tension of the curve. fillmode Type: System.Drawing.Drawing2D..::.FillMode Member of the FillMode enumeration that determines how the curve is filled. This parameter is required but ignored. private void DrawClosedCurvePointTension(PaintEventArgs e) { // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3);

Page 49: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 49

// Create points that define curve. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Create tension and fill mode. float tension = 1.0F; FillMode aFillMode = FillMode.Alternate; // Draw closed curve to screen. e.Graphics.DrawClosedCurve(greenPen, curvePoints, tension, aFillMode); } public void DrawClosedCurve( Pen pen, PointF[] points, float tension, FillMode fillmode ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.PointF>[]()[] Array of PointF structures that define the spline. tension Type: System..::.Single Value greater than or equal to 0.0F that specifies the tension of the curve. fillmode Type: System.Drawing.Drawing2D..::.FillMode Member of the FillMode enumeration that determines how the curve is filled. This parameter is required but is ignored. private void DrawClosedCurvePointFTension(PaintEventArgs e) { // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3);

Page 50: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 50

// Create points that define curve. PointF point1 = new PointF(50.0F, 50.0F); PointF point2 = new PointF(100.0F, 25.0F); PointF point3 = new PointF(200.0F, 5.0F); PointF point4 = new PointF(250.0F, 50.0F); PointF point5 = new PointF(300.0F, 100.0F); PointF point6 = new PointF(350.0F, 200.0F); PointF point7 = new PointF(250.0F, 250.0F); PointF[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Create tension and fill mode. float tension = 1.0F; FillMode aFillMode = FillMode.Alternate; // Draw closed curve to screen. e.Graphics.DrawClosedCurve(greenPen, curvePoints, tension, aFillMode); }

9.1.5 DrawCurve Method Draws a cardinal spline through a specified array of Point structures. public void DrawCurve( Pen pen, Point[] points ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that define the spline. private void DrawCurvePoint(PaintEventArgs e) { // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3); // Create points that define curve. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50);

Page 51: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 51

Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Draw curve to screen. e.Graphics.DrawCurve(greenPen, curvePoints); } Graphics..::.DrawCurve Method (Pen, array<Point>[]()[], Single) Draws a cardinal spline through a specified array of Point structures using a specified tension. public void DrawCurve( Pen pen, Point[] points, float tension ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and height of the curve. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that define the spline. tension Type: System..::.Single Value greater than or equal to 0.0F that specifies the tension of the curve. private void DrawCurvePointTension(PaintEventArgs e) { // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3); // Create points that define curve. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = {point1, point2, point3, point4, point5, point6, point7};

Page 52: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 52

// Draw lines between original points to screen. e.Graphics.DrawLines(redPen, curvePoints); // Create tension. float tension = 1.0F; // Draw curve to screen. e.Graphics.DrawCurve(greenPen, curvePoints, tension); }

9.1.6 DrawEllipse public void DrawEllipse( Pen pen, Rectangle rect ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the ellipse. rect Type: System.Drawing..::.Rectangle Rectangle structure that defines the boundaries of the ellipse. private void DrawEllipseRectangle(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create rectangle for ellipse. Rectangle rect = new Rectangle(0, 0, 200, 100); // Draw ellipse to screen. e.Graphics.DrawEllipse(blackPen, rect); } public void DrawEllipse( Pen pen, int x, int y, int width, int height ) private void DrawEllipseInt(PaintEventArgs e) {

Page 53: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 53

// Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create location and size of ellipse. int x = 0; int y = 0; int width = 200; int height = 100; // Draw ellipse to screen. e.Graphics.DrawEllipse(blackPen, x, y, width, height); }

9.1.7 DrawLine public void DrawLine( Pen pen, Point pt1, Point pt2 ) public void DrawLinePoint(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create points that define line. Point point1 = new Point(100, 100); Point point2 = new Point(500, 100); // Draw line to screen. e.Graphics.DrawLine(blackPen, point1, point2); } public void DrawLine( Pen pen, int x1, int y1, int x2, int y2 ) public void DrawLineInt(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3);

Page 54: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 54

// Create coordinates of points that define line. int x1 = 100; int y1 = 100; int x2 = 500; int y2 = 100; // Draw line to screen. e.Graphics.DrawLine(blackPen, x1, y1, x2, y2); }

9.1.8 DrawLines Draws a series of line segments that connect an array of Point structures. public void DrawLines( Pen pen, Point[] points ) public void DrawLinesPoint(PaintEventArgs e) { // Create pen. Pen pen = new Pen(Color.Black, 3); // Create array of points that define lines to draw. Point[] points = { new Point(10, 10), new Point(10, 100), new Point(200, 50), new Point(250, 300) }; //Draw lines to screen. e.Graphics.DrawLines(pen, points); }

9.1.9 DrawPath Draws a GraphicsPath. public void DrawPath( Pen pen, GraphicsPath path )

Page 55: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 55

Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the path. path Type: System.Drawing.Drawing2D..::.GraphicsPath GraphicsPath to draw. public void DrawPathEllipse(PaintEventArgs e) { // Create graphics path object and add ellipse. GraphicsPath graphPath = new GraphicsPath(); graphPath.AddEllipse(0, 0, 200, 100); // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Draw graphics path to screen. e.Graphics.DrawPath(blackPen, graphPath); }

9.1.10 DrawPie Draws a pie shape defined by an ellipse specified by a coordinate pair, a width, a height, and two radial lines. public void DrawPie( Pen pen, Rectangle rect, float startAngle, float sweepAngle ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the pie shape. rect Type: System.Drawing..::.Rectangle Rectangle structure that represents the bounding rectangle that defines the ellipse from which the pie shape comes.

Page 56: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 56

startAngle Type: System..::.Single Angle measured in degrees clockwise from the x-axis to the first side of the pie shape. sweepAngle Type: System..::.Single Angle measured in degrees clockwise from the startAngle parameter to the second side of the pie shape. public void DrawPieRectangle(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create rectangle for ellipse. Rectangle rect = new Rectangle(0, 0, 200, 100); // Create start and sweep angles. float startAngle = 0.0F; float sweepAngle = 45.0F; // Draw pie to screen. e.Graphics.DrawPie(blackPen, rect, startAngle, sweepAngle); } public void DrawPie( Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle ) Parameters pen Type: System.Drawing..::.Pen Pen that determines the color, width, and style of the pie shape. x Type: System..::.Int32 The x-coordinate of the upper-left corner of the bounding rectangle that defines the ellipse from which the pie shape comes. y Type: System..::.Int32

Page 57: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 57

The y-coordinate of the upper-left corner of the bounding rectangle that defines the ellipse from which the pie shape comes. width Type: System..::.Int32 Width of the bounding rectangle that defines the ellipse from which the pie shape comes. height Type: System..::.Int32 Height of the bounding rectangle that defines the ellipse from which the pie shape comes. startAngle Type: System..::.Int32 Angle measured in degrees clockwise from the x-axis to the first side of the pie shape. sweepAngle Type: System..::.Int32 Angle measured in degrees clockwise from the startAngle parameter to the second side of the pie shape. public void DrawPieInt(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create location and size of ellipse. int x = 0; int y = 0; int width = 200; int height = 100; // Create start and sweep angles. int startAngle = 0; int sweepAngle = 45; // Draw pie to screen. e.Graphics.DrawPie(blackPen, x, y, width, height, startAngle, sweepAngle); }

9.1.11 DrawPolygon public void DrawPolygon( Pen pen, Point[] points ) public void DrawPolygonPoint(PaintEventArgs e) { // Create pen.

Page 58: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 58

Pen blackPen = new Pen(Color.Black, 3); // Create points that define polygon. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = { point1, point2, point3, point4, point5, point6, point7 }; // Draw polygon to screen. e.Graphics.DrawPolygon(blackPen, curvePoints); }

Abbildung 5 Beispiel mit DrawPolygon

9.1.12 DrawRectangle public void DrawRectangle( Pen pen, Rectangle rect ) public void DrawRectangleRectangle(PaintEventArgs e) {

Page 59: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 59

// Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create rectangle. Rectangle rect = new Rectangle(0, 0, 200, 200); // Draw rectangle to screen. e.Graphics.DrawRectangle(blackPen, rect); } public void DrawRectangle( Pen pen, int x, int y, int width, int height ) public void DrawRectangleInt(PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create location and size of rectangle. int x = 0; int y = 0; int width = 200; int height = 200; // Draw rectangle to screen. e.Graphics.DrawRectangle(blackPen, x, y, width, height); }

9.2 DrawString-Methoden

9.2.1 DrawString public void DrawString( string s, Font font, Brush brush, PointF point ) public void DrawStringPointF(PaintEventArgs e)

Page 60: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 60

{ // Create string to draw. String drawString = "Sample Text"; // Create font and brush. Font drawFont = new Font("Arial", 16); SolidBrush drawBrush = new SolidBrush(Color.Black); // Create point for upper-left corner of drawing. PointF drawPoint = new PointF(150.0F, 150.0F); // Draw string to screen. e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint); }

9.2.2 DrawString(String, Font, Brush, PointF, StringFormat) Graphics..::.DrawString Method (String, Font, Brush, PointF, StringFormat) Draws the specified text string at the specified location with the specified Brush and Font objects using the formatting attributes of the specified StringFormat. public void DrawString( string s, Font font, Brush brush, PointF point, StringFormat format ) Parameters s Type: System..::.String String to draw. font Type: System.Drawing..::.Font Font that defines the text format of the string. brush Type: System.Drawing..::.Brush Brush that determines the color and texture of the drawn text. point Type: System.Drawing..::.PointF PointF structure that specifies the upper-left corner of the drawn text.

Page 61: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 61

format Type: System.Drawing..::.StringFormat StringFormat that specifies formatting attributes, such as line spacing and alignment, that are applied to the drawn text. public void DrawStringPointFFormat(PaintEventArgs e) { // Create string to draw. String drawString = "Sample Text"; // Create font and brush. Font drawFont = new Font("Arial", 16); SolidBrush drawBrush = new SolidBrush(Color.Black); // Create point for upper-left corner of drawing. PointF drawPoint = new PointF(150.0F, 50.0F); // Set format of string. StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags = StringFormatFlags.DirectionVertical; // Draw string to screen. e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint, drawFormat); }

9.3 Fill-Methoden

9.3.1 FillClosedCurve public void FillClosedCurve( Brush brush, Point[] points ) public void FillClosedCurvePoint(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); //Create array of points for curve. Point point1 = new Point(100, 100); Point point2 = new Point(200, 50); Point point3 = new Point(250, 200); Point point4 = new Point(50, 150);

Page 62: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 62

Point[] points = {point1, point2, point3, point4}; // Fill curve on screen. e.Graphics.FillClosedCurve(redBrush, points); } public void FillClosedCurve( Brush brush, Point[] points, FillMode fillmode ) Parameters brush Type: System.Drawing..::.Brush Brush that determines the characteristics of the fill. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that define the spline. fillmode Type: System.Drawing.Drawing2D..::.FillMode Member of the FillMode enumeration that determines how the curve is filled. Alternate Specifies the alternate fill mode. Winding Specifies the winding fill mode. public void FillClosedCurvePointFillMode(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); //Create array of points for curve. Point point1 = new Point(100, 100); Point point2 = new Point(200, 50); Point point3 = new Point(250, 200); Point point4 = new Point(50, 150); Point[] points = {point1, point2, point3, point4}; // Set fill mode. FillMode newFillMode = FillMode.Winding; // Fill curve on screen. e.Graphics.FillClosedCurve(redBrush, points, newFillMode); }

9.3.2 FillEllipse

Page 63: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 63

public void FillEllipse( Brush brush, Rectangle rect ) public void FillEllipseRectangle(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); // Create rectangle for ellipse. int x = 0; int y = 0; int width = 200; int height = 100; Rectangle rect = new Rectangle(x, y, width, height); // Fill ellipse on screen. e.Graphics.FillEllipse(redBrush, rect); } public void FillEllipse( Brush brush, int x, int y, int width, int height ) public void FillEllipseInt(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); // Create location and size of ellipse. int x = 0; int y = 0; int width = 200; int height = 100; // Fill ellipse on screen. e.Graphics.FillEllipse(redBrush, x, y, width, height); }

9.3.3 FillPath

Page 64: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 64

public void FillPath( Brush brush, GraphicsPath path ) public void FillPathEllipse(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); // Create graphics path object and add ellipse. GraphicsPath graphPath = new GraphicsPath(); graphPath.AddEllipse(0, 0, 200, 100); // Fill graphics path to screen. e.Graphics.FillPath(redBrush, graphPath); }

9.3.4 FillPie public void FillPie( Brush brush, Rectangle rect, float startAngle, float sweepAngle ) Parameters brush Type: System.Drawing..::.Brush Brush that determines the characteristics of the fill. rect Type: System.Drawing..::.Rectangle Rectangle structure that represents the bounding rectangle that defines the ellipse from which the pie section comes. startAngle Type: System..::.Single Angle in degrees measured clockwise from the x-axis to the first side of the pie section. sweepAngle Type: System..::.Single Angle in degrees measured clockwise from the startAngle parameter to the second side of the pie section.

Page 65: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 65

public void FillPieRectangle(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); // Create rectangle for ellipse. Rectangle rect = new Rectangle(0, 0, 200, 100); // Create start and sweep angles. float startAngle = 0.0F; float sweepAngle = 45.0F; // Fill pie to screen. e.Graphics.FillPie(redBrush, rect, startAngle, sweepAngle); } public void FillPie( Brush brush, int x, int y, int width, int height, int startAngle, int sweepAngle ) Parameters brush Type: System.Drawing..::.Brush Brush that determines the characteristics of the fill. x Type: System..::.Int32 The x-coordinate of the upper-left corner of the bounding rectangle that defines the ellipse from which the pie section comes. y Type: System..::.Int32 The y-coordinate of the upper-left corner of the bounding rectangle that defines the ellipse from which the pie section comes. width Type: System..::.Int32 Width of the bounding rectangle that defines the ellipse from which the pie section comes. height Type: System..::.Int32 Height of the bounding rectangle that defines the ellipse from which the pie section comes. startAngle Type: System..::.Int32

Page 66: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 66

Angle in degrees measured clockwise from the x-axis to the first side of the pie section. sweepAngle Type: System..::.Int32 Angle in degrees measured clockwise from the startAngle parameter to the second side of the pie section. public void FillPieInt(PaintEventArgs e) { // Create solid brush. SolidBrush redBrush = new SolidBrush(Color.Red); // Create location and size of ellipse. int x = 0; int y = 0; int width = 200; int height = 100; // Create start and sweep angles. int startAngle = 0; int sweepAngle = 45; // Fill pie to screen. e.Graphics.FillPie(redBrush, x, y, width, height, startAngle, sweepAngle); }

9.3.5 FillPolygon public void FillPolygon( Brush brush, Point[] points ) public void FillPolygonPoint(PaintEventArgs e) { // Create solid brush. SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create points that define polygon. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Draw polygon to screen. e.Graphics.FillPolygon(blueBrush, curvePoints);

Page 67: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 67

} public void FillPolygon( Brush brush, Point[] points, FillMode fillMode ) Parameters brush Type: System.Drawing..::.Brush Brush that determines the characteristics of the fill. points Type: array<System.Drawing..::.Point>[]()[] Array of Point structures that represent the vertices of the polygon to fill. fillMode Type: System.Drawing.Drawing2D..::.FillMode Member of the FillMode enumeration that determines the style of the fill. public void FillPolygonPointFillMode(PaintEventArgs e) { // Create solid brush. SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create points that define polygon. Point point1 = new Point(50, 50); Point point2 = new Point(100, 25); Point point3 = new Point(200, 5); Point point4 = new Point(250, 50); Point point5 = new Point(300, 100); Point point6 = new Point(350, 200); Point point7 = new Point(250, 250); Point[] curvePoints = {point1, point2, point3, point4, point5, point6, point7}; // Define fill mode. FillMode newFillMode = FillMode.Winding; // Draw polygon to screen. e.Graphics.FillPolygon(blueBrush, curvePoints, newFillMode); }

9.3.6 FillRectangle public void FillRectangle( Brush brush, Rectangle rect

Page 68: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 68

) private void FillRectangleRectangle(PaintEventArgs e) { // Create solid brush. SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create rectangle. Rectangle rect = new Rectangle(0, 0, 200, 200); // Fill rectangle to screen. e.Graphics.FillRectangle(blueBrush, rect); } public void FillRectangle( Brush brush, int x, int y, int width, int height ) private void FillRectangleInt(PaintEventArgs e) { // Create solid brush. SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create location and size of rectangle. int x = 0; int y = 0; int width = 200; int height = 200; // Fill rectangle to screen. e.Graphics.FillRectangle(blueBrush, x, y, width, height); }

9.3.7 FillRegion public void FillRegion( Brush brush, Region region ) Parameters

Page 69: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 69

brush Type: System.Drawing..::.Brush Brush that determines the characteristics of the fill. region Type: System.Drawing..::.Region Region that represents the area to fill. private void FillRegionRectangle(PaintEventArgs e) { // Create solid brush. SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create rectangle for region. Rectangle fillRect = new Rectangle(100, 100, 200, 200); // Create region for fill. Region fillRegion = new Region(fillRect); // Fill region to screen. e.Graphics.FillRegion(blueBrush, fillRegion); }

9.4 DrawImage

9.4.1 DrawImage public void DrawImage( Image image, Point point ) private void DrawImagePoint(PaintEventArgs e) { // Create image. Image newImage = Image.FromFile("SampImag.jpg"); // Create Point for upper-left corner of image. Point ulCorner = new Point(100, 100); // Draw image to screen. e.Graphics.DrawImage(newImage, ulCorner); } public void DrawImage( Image image, int x, int y

Page 70: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 70

) public void DrawImage2Int(PaintEventArgs e) { // Create image. Image newImage = Image.FromFile("SampImag.jpg"); // Create coordinates for upper-left corner of image. int x = 100; int y = 100; // Draw image to screen. e.Graphics.DrawImage(newImage, x, y); } public void DrawImage( Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr ) Parameters image Type: System.Drawing..::.Image Image to draw. destPoints Type: array<System.Drawing..::.Point>[]()[] Array of three Point structures that define a parallelogram. srcRect Type: System.Drawing..::.Rectangle Rectangle structure that specifies the portion of the image object to draw. srcUnit Type: System.Drawing..::.GraphicsUnit Member of the GraphicsUnit enumeration that specifies the units of measure used by the srcRect parameter. imageAttr Type: System.Drawing.Imaging..::.ImageAttributes ImageAttributes that specifies recoloring and gamma information for the image object. private void DrawImageParaRectAttrib(PaintEventArgs e) {

Page 71: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 71

// Create image. Image newImage = Image.FromFile("SampImag.jpg"); // Create parallelogram for drawing image. Point ulCorner1 = new Point(100, 100); Point urCorner1 = new Point(325, 100); Point llCorner1 = new Point(150, 250); Point[] destPara1 = {ulCorner1, urCorner1, llCorner1}; // Create rectangle for source image. Rectangle srcRect = new Rectangle(50, 50, 150, 150); GraphicsUnit units = GraphicsUnit.Pixel; // Draw original image to screen. e.Graphics.DrawImage(newImage, destPara1, srcRect, units); // Create parallelogram for drawing adjusted image. Point ulCorner2 = new Point(325, 100); Point urCorner2 = new Point(550, 100); Point llCorner2 = new Point(375, 250); Point[] destPara2 = {ulCorner2, urCorner2, llCorner2}; // Create image attributes and set large gamma. ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetGamma(4.0F); // Draw adjusted image to screen. e.Graphics.DrawImage(newImage, destPara2, srcRect, units, imageAttr); }

Page 72: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 72

9.5 Brush

9.5.1 SolidBrush SolidBrush drawBrush = new SolidBrush(Color.Black);

9.5.2 HatchBrush Brush mybrush = new HatchBrush( HatchStyle.DiagonalCross, Color.Green );

9.5.2.1 HatchStyle Member name Description BackwardDiagonal A pattern of lines on a diagonal from upper right to lower left. Cross Specifies horizontal and vertical lines that cross. DarkDownwardDiagonal Specifies diagonal lines that slant to the right from top points to

bottom points, are spaced 50 percent closer together than, and are twice the width of ForwardDiagonal. This hatch pattern is not antialiased.

DarkHorizontal Specifies horizontal lines that are spaced 50 percent closer together than Horizontal and are twice the width of HatchStyleHorizontal.

DarkUpwardDiagonal Specifies diagonal lines that slant to the left from top points to bottom points, are spaced 50 percent closer together than BackwardDiagonal, and are twice its width, but the lines are not antialiased.

DarkVertical Specifies vertical lines that are spaced 50 percent closer together than Vertical and are twice its width.

DashedDownwardDiagonal Specifies dashed diagonal lines, that slant to the right from top points to bottom points.

DashedHorizontal Specifies dashed horizontal lines. DashedUpwardDiagonal Specifies dashed diagonal lines, that slant to the left from top points

to bottom points. DashedVertical Specifies dashed vertical lines. DiagonalBrick Specifies a hatch that has the appearance of layered bricks that slant

to the left from top points to bottom points. DiagonalCross Specifies forward diagonal and backward diagonal lines that cross.

The lines are antialiased. Divot Specifies a hatch that has the appearance of divots. DottedDiamond Specifies forward diagonal and backward diagonal lines, each of

which is composed of dots, that cross. DottedGrid Specifies horizontal and vertical lines, each of which is composed of

dots, that cross. ForwardDiagonal A pattern of lines on a diagonal from upper left to lower right. Horizontal A pattern of horizontal lines. HorizontalBrick Specifies a hatch that has the appearance of horizontally layered

bricks.

Page 73: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 73

LargeCheckerBoard Specifies a hatch that has the appearance of a checkerboard with squares that are twice the size of SmallCheckerBoard.

LargeConfetti Specifies a hatch that has the appearance of confetti, and is composed of larger pieces than SmallConfetti.

LargeGrid Specifies the hatch style Cross. LightDownwardDiagonal LightHorizontal Specifies horizontal lines that are spaced 50 percent closer together

than Horizontal. LightUpwardDiagonal Specifies diagonal lines that slant to the left from top points to bottom

points and are spaced 50 percent closer together than BackwardDiagonal, but they are not antialiased.

LightVertical Specifies vertical lines that are spaced 50 percent closer together than Vertical.

Max Specifies hatch style SolidDiamond. Min Specifies hatch style Horizonal. NarrowHorizontal Specifies horizontal lines that are spaced 75 percent closer together

than hatch style Horizontal (or 25 percent closer together than LightHorizontal).

NarrowVertical Specifies vertical lines that are spaced 75 percent closer together than hatch style Vertical (or 25 percent closer together than LightVertical).

OutlinedDiamond Specifies forward diagonal and backward diagonal lines that cross but are not antialiased.

Percent05 Specifies a 5-percent hatch. The ratio of foreground color to background color is 5:100.

Percent10 Specifies a 10-percent hatch. The ratio of foreground color to background color is 10:100.

Percent20 Specifies a 20-percent hatch. The ratio of foreground color to background color is 20:100.

Percent25 Specifies a 25-percent hatch. The ratio of foreground color to background color is 25:100.

Percent30 Specifies a 30-percent hatch. The ratio of foreground color to background color is 30:100.

Percent40 Specifies a 40-percent hatch. The ratio of foreground color to background color is 40:100.

Percent50 Specifies a 50-percent hatch. The ratio of foreground color to background color is 50:100.

Percent60 Specifies a 60-percent hatch. The ratio of foreground color to background color is 60:100.

Percent70 Specifies a 70-percent hatch. The ratio of foreground color to background color is 70:100.

Percent75 Specifies a 75-percent hatch. The ratio of foreground color to background color is 75:100.

Percent80 Specifies a 80-percent hatch. The ratio of foreground color to background color is 80:100.

Percent90 Specifies a 90-percent hatch. The ratio of foreground color to background color is 90:100.

Plaid Specifies a hatch that has the appearance of a plaid material. Shingle Specifies a hatch that has the appearance of diagonally-layered

shingles that slant to the right from top points to bottom points. SmallCheckerBoard Specifies a hatch that has the appearance of a checkerboard. SmallConfetti Specifies a hatch that has the appearance of confetti. SmallGrid Specifies horizontal and vertical lines that cross and are spaced 50

percent closer together than hatch style Cross. SolidDiamond Specifies a hatch that has the appearance of a checkerboard placed

diagonally.

Page 74: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 74

Sphere Specifies a hatch that has the appearance of spheres laid adjacent to one another.

Trellis Specifies a hatch that has the appearance of a trellis. Vertical A pattern of vertical lines. Wave Specifies horizontal lines that are composed of tildes. Weave Specifies a hatch that has the appearance of a woven material. WideDownwardDiagonal Specifies diagonal lines that slant to the right from top points to

bottom points, have the same spacing as hatch style ForwardDiagonal, and are triple its width, but are not antialiased.

WideUpwardDiagonal Specifies diagonal lines that slant to the left from top points to bottom points, have the same spacing as hatch style BackwardDiagonal, and are triple its width, but are not antialiased.

ZigZag Specifies horizontal lines that are composed of zigzags. Beispiel: Brush mybrush1 = new HatchBrush(HatchStyle.DiagonalCross, Color.Green); g.FillEllipse(mybrush1, 152, 112, 150, 80); Brush mybrush2 = new HatchBrush(HatchStyle.ZigZag, Color.Red); g.FillEllipse(mybrush2, 10, 11, 120, 80);

9.5.3 LinearGradientBrush Brush mybrush = new LinearGradientBrush( point, point, Color, Color ); Beispiel: Point p1 = new Point(0, 0); Point p2 = new Point(200, 100); // Größe des Farbschemas, je größer, desto feiner mybrush = new LinearGradientBrush( p1, p2, Color.Red, Color.Blue ); g.FillEllipse(mybrush, 50, 50, 300, 200);

Page 75: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 75

9.6 Font public void Font( string Fontname, float emSize); public void Font( string Fontname, float emSize, FontStyle style ); FontStyle: jeweils mit eine Bitweisen Oder verknüpfen (GDI1)

• Bold • Underline • Italic • Strikeout • Regular

Beispiele: Font drawFont1 = new Font("Arial", 16); Font drawFont2 = new Font(„Courier New", 16, FontStyle.Bold | FontStyle.Underline ); SolidBrush drawBrush = new SolidBrush(Color.Black); PointF drawPoint = new PointF(50.0F, 55.0F); g.DrawString("Hier ist ein Text", drawFont1, drawBrush, drawPoint); g.DrawString("Hier ist zweiter Text", drawFont2, drawBrush, new PointF(50.0F, 85.0F) );

Page 76: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 76

10 Indexverzeichnis

. .net 5

A Ausgabe 12

B Beispiele 7 Brush 72

C C# 5 catch 15 Console 12

D Datentypen 8 Dekonstruktor 16 Delegates 14 DrawArc 42 DrawBezier 43 DrawBeziers 45 DrawCloseCurve 46 DrawCurve 50 DrawEllipse 52 DrawImage 69 DrawLine 53 DrawLines 54 DrawPath 54 DrawPie 55 DrawPolygon 57, 58 DrawString 59, 60

E Eigenschaften 5 Einführung 5 Eingabe 12 else 9 Enumerationen 10

F FillClosedCurve 61 FillEllipse 62 FillPath 63 FillPie 64 FillPolygon 66 FillRectangle 67 FillRegion 68 Font 75 foreach 10 Formatierte Ausgaben 12

Page 77: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 77

G Get-Methodenr 17 Grafik 42 Grunddialoge 29

H HatchBrush 72 HatchStyle 72 Hello World 7

I if 9

K Konstruktor 16

L LinearGradientBrush 74

M MessageBox 29

Gesamtüberblick 30 MessageBoxDefaultButton 29 MessageBoxIcon 29

O Objektorientierte Programmierung 16 OOP 16

Beispiel Koerper 25 Beispiel punkt-linie 24 Beispiele 24 Dekonstruktor 16 Get-Methodenr 17 Interface 20 Konstruktor 16 Neue Klassendatei 18 Operator Overloading 20 Set-Methodenr 17 Überschriebene Methodenr 17

Operator Overloading 20

P Parameterübergabe 13

S Set-Methodenr 17 SolidBrush 72 String-Befehle 8 switch 9 Syntax 8

T try 15

Page 78: „Visual Studio mit C# Grundlagen Stand 31.01 · Die Format-Anweisung ist ähnlich der printf aus C bzw. Java zu lesen. Die Platzhalter sind aber in der Erstellen des Beispiels •

Hochschule Harz FB Automatisierung und Informatik Seite 78

W while 9