C#
Lösungen einiger C# Probleme

Stichworte Problem Lösung
Tab´s in Editoren Tab´s in Editoren freischalten TextBox:
editor.AcceptsReturn = true;
editor.AcceptsTab = true;
editor.Multiline = true;
editor.ScrollBars = System.Windows.Forms.ScrollBars.Both;
editor.TabStop = false;
editor.WordWrap = false;
editor.MaxLength = 327670;

RichTextBox:
richTextBox1.AcceptsTab = true;
richTextBox1.Multiline = true;
richTextBox1.TabStop = false;
richTextBox1.WordWrap = false;
richTextBox1.MaxLength = 327670;
How can I create a new String? Eine Stringvariable wird in einer Schleife benutzt.
Es muss in jedem Durchlauf eine neue Referenz erzeugt werden.
String refString = "";
while (...) {
__refString = readText();
__liste.Add( refString.Clone() );
}
Konvertierung String nach Double
Convert
ToDouble
Folgende Zahl x1 wird falsch konvertiert:
Die Zahl x2 wird richtig konvertiert

double x1, x2;
String sStr1 = "123.456";
String sStr2 = "123,456";
x1 = Convert.ToDouble(sStr1);
x2 = Convert.ToDouble(sStr2);

Ursache: .net nimmt immer den Dezimaltrenner aus der Systemeinstellung
double x1, x2;
String sStr1 = "123.456";
String sStr2 = "123,456";
tryparse doesn't like space!! use Trim()
x1 = Convert.ToDouble(sStr1, System.Globalization.CultureInfo.InvariantCulture);
x2 = Convert.ToDouble(sStr2, System.Globalization.CultureInfo.InvariantCulture);
if (double.TryParse(textBox1.Text, System.Globalization.
NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out value1) {
}

bei negativen Zahlen, speziell decimal:

if (double.TryParse(textBox1.Text, System.Globalization.
NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.CultureInfo.InvariantCulture,
out value1) {
}
Konvertierung von Double nach String
ToString
Das Problem ist, das man den Punkt angibt, trotzdem ein Kommagesetzt wird (In Germany) Double d = 10.45678;
string sd = d.ToString("##0.############");
Liefert 10,45678
string sd = d.ToString("##0.############", System.Globalization.CultureInfo.InvariantCulture);
Liefert 10.45678
Hex nach int Eine hexadezimale Zahl in einem Int umwandeln int value = 0;
String input = "0x21"; // Eingangswert
String sHex = input.Substring(2); // 0x abschneiden
if (int.TryParse(sHex,System.Globalization.NumberStyles.HexNumber,
__System.Globalization.CultureInfo.InvariantCulture, out value)) {
____cell.ToolTipText = value.ToString();
}
instanceof instance heisst in C# is, sonst ändert sich nix Beispiel: test_is.cs

CQuadrat q1 = new CQuadrat(5);
CRechteck r1 = new CRechteck(5, 3);
Object obj = q1;
if (obj is CQuadrat)
{
CQuadrat q = (CQuadrat)obj;
}
super super heisst in C# this, sonst ändert sich nix public student() : this(0)
{
}

public student(int Matrnr)
{
m_Matrnr = Matrnr;
}
Start
Run
Execute
Aufruf
Start eines Programms
einer E-Mail-Adresse
einer HTML-Seite
using System.Diagnostics; // run

Process Prog = new Process();
Prog.StartInfo.FileName = "mailto:mwilhelm@hs-harz.de";
Prog.StartInfo.Arguments = "";
Prog.Start();
Prog.Close();

Process Prog = new Process();
Prog.StartInfo.FileName = "http://mwilhelm.hs-harz.de";
Prog.StartInfo.Arguments = "";
Prog.Start();
Prog.Close();

Process Prog = new Process();
Prog.StartInfo.FileName = "notepad.exe";
Prog.StartInfo.Arguments = "C:\\Daten\\test.txt";
Prog.Start();
Prog.Close();
Process Prog = new Process();
Prog.StartInfo.FileName = "myprogram.exe";
Prog.StartInfo.Arguments = "C:\\Daten\\test.txt";
Prog.Start();
Prog.WaitForExit(); // wait for the process
Prog.Close();
Popupmenu
Mouse click
Dynamisch erstellte Elemente
Wie kann man bei mehreren automatisch erstellten Schaltern / Bilder / Componenten ein Popupmenü an der richtigen Stelle aufrufen Form1.cs
Krocker.exe
krocker.zip



Random
Zufallszahlen
Erzeugen verschiedener Zufallszahlen Random rand = new Random();
int initValue = 10;
Random rand = new Random(initValue);
for (int j = 0; j < 6; j++)
Console.Writeline(" {0,10} ", rand.Next(0,10));

rand.Next(von,bis)
toString
Format
Ausgabe eines Double-Wertes mittels der Methode toString double x=1234.567;
Edit.Text = x.ToString("#.##"); 1234,57
Edit.Text = x.ToString("00000"); 01235 (Rundung)
Edit.Text = x.ToString("#"); 1235 (Rundung)
Edit.Text = x.ToString("#,###"); 1.235 (Rundung, Tausender-Trennung)
Edit.Text = x.ToString("#.##E+00"); 1.23E+03 (Rundung)
GroupBox
Button
Checked
UnChecked
RadioButton
In einer ToolStrip-Leiste sollen Schalter sich gegenseitig ausschalten, à la RadioButton // Gemeinsame Methode zum Löschen aller Schalter
// dann setzen EINES Schalters
private void setToolBarButtons(ToolStripButton BnActive)
{
Bn1.CheckState = System.Windows.Forms.CheckState.Unchecked;
Bn2.CheckState = System.Windows.Forms.CheckState.Unchecked;
BnActive.CheckState = System.Windows.Forms.CheckState.Checked;
}
private void Bn1_Click(object sender, EventArgs e)
{
setToolBarButtons(Bn1);
}

private void Bn2_Click(object sender, EventArgs e)
{
setToolBarButtons(Bn2);
}
split eines Strings Die TextBox hat keine Zeilen.
Wie kann man den gesamten Text in Zeilen aufteilen?
public static String[] getLines(String text) {
__StringBuilder sb = new StringBuilder();
__string[] splitStrings = { "\r\n" }; // alternatives Splitten { "\r", "\r\n", "\n" };
__return text.Split(splitStrings, StringSplitOptions.None);
}
Clipboard
setzen
holen
Zugriff auf die Zwischenablage setzen:
Clipboard.SetDataObject("hier ein Text");

holen:
sStr = (string) ClipBoard.GetDataObject( typeof(string) );
OpenDialog OpenDialog mit Startverzeichnis setzen openFileDialog1.InitialDirectory = System.Environment.CurrentDirectory;
ColorDialog ColorDialog setzen, starten und die Farbe erhalten ColorDialog coldialog = new ColorDialog();
coldialog.FullOpen = true;
coldialog.Color=PanelColor.BackColor;
if (coldialog.ShowDialog() == DialogResult.OK)
{
PanelColor.BackColor = coldialog.Color;
}
foreach TabPages Iteration über alle TabPages TextBox Editor2;
int i=0;
foreach (TabPage page in MainTab.TabPages)
{
i++;
Editor2 = (TextBox)page.GetNextControl(page,true);
Editor2.text = "Editor: "+i;
}
TreeNode im TreeView setzen Wie kann man einen Knoten im TreeView setzen? chkTree.SelectedNode = node ((c) by Beck)
MVC-Modell Fertiges Beispiel eines MDI-Programms mit selbst-erstelltem MVC-Modell. Verwendet wurde das Java-Modell mit Ableitung und Interface. Es kann also angepasst werden. mdi_mvc.7z
MDI-Fenster Bestimmen des aktiven Elementes private ChildForm getActiceForm() {
Form form = this.ActiveMdiChild;
if (form==null)
return null;
else
return (ChildForm) form;
}
System.Environment Wichtige Elemente aus System.Environment System.Environment.CommandLine
System.Environment.CurrentDirectory
System.Environment.GetCommandLineArgs als String
System.Environment.GetEnvironmentVariables
System.Environment.GetLogicalDrives
System.Environment.GetFolderPath
System.Environment.MachineName
System.Environment.OSVersion
System.Environment.SpecialFolder
System.Environment.SystemDirectory
System.Environment.UserName
System.Environment.ProcessorCount

Anwendung:
String path= Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
path.Replace("Desktop", "Downloads");
Explorer Bestimmen der Laufwerke
Bestimmen der Verzeichnisse
Bestimmen der Dateien
String[] lws = System.Environment.GetLogicalDrives();
foreach (String lw in lws) {
_node = new TreeNode(lw, 3, 4);
_root.Nodes.Add(node);
// Abfrage, ob CD eingelegt ?
if (Directory.Exists(lw)) {
_string[] subdir = Directory.GetDirectories(lw);
_string[] files = Directory.GetFiles(lw);
foreach (String file in files) {
_FileAttributes fileAttributes = File.GetAttributes(file);
_bool isReadOnly = (fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
}
} // if
} // foreach (String lw in lws)
Einlesen von Text
Codierung eines Textes
437 / 850 / Ansi / utf
Welche Codierungen sind beim Einlesen möglich?
(Encoding)
String[] lines = File.ReadAllLines(filename, Encoding.GetEncoding(850));
String[] lines = File.ReadAllText(filename, System.Text.Encoding.ASCII);
System.Text.Encoding.ASCII
System.Text.Encoding.BigEndianUnicode
System.Text.Encoding.Unicode
System.Text.Encoding.UTF32
System.Text.Encoding.UTF7
System.Text.Encoding.UTF8
Encoding.GetEncoding( 850):
Encoding.GetEncoding( 437):
Encoding.GetEncoding("ISO-8859-1") // Delphi, DOS-Texte

//Lese und Schreiben in der gleichen Codierung
Encoding code = System.Text.Encoding.GetEncoding(850);
String text = File.ReadAllText(source, code);
File.WriteAllText(dest, text, code);
Kopieren und Ausschneiden à Explorer Wie kann man die Shell-Copy/Paste-Funktionen einbinden Beispiel:
FileOperationAPIWrapper.txt
Lesen oder Schreiben eines Delphi-Records in C# Definition eines Record in C# Man verwendet eine struct mit pack=1
Die festen Strings in Delphi können über ein Längenbyte und ein Array erfasst werden.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
private struct MyRecord {
public int hwnd;
public double size;
public bool gender;
public byte stringlaenge;
public char[] name;

// Arrays werden mit einem Konstruktor initialisert
public MyRecord(int anz) {
hwnd = 0;
size = 0;
gender = true;
stringlaenge = 0;
name = new char[anz];
}
}
IBAN-Rechner Ermitteln der IBan-Nummer iban.txt
dateierweiterung betriebssystem zuweisung programm
fileextention operationssystem program
Zuweisen einer Dateierweiterung zu einem Programm string ext = ".grf";
string title = "Grafikprogramm";
string extdescription = "Ein Grafikprogramm";
FileRegistrationHelper.SetFileAssociation(@"D:\CAD\CAD.exe", ext, title + "." + extdescription);

FileRegistrationHelper.txt
recursive filecopy without SHFILEOPSTRUCT How can I copy files and directories without the Windows filecopy DLL? Source-code:
DirectoryCopy.txt

Project:
DirectoryCopy.zip

Image:
DirectoryCopy.png
C# tempfile How can I get a tempfile? public static String getTempFile() {
__return System.IO.Path.GetTempFileName();
}



Literatur C#

Visual C# 2012
Doberanz, Gewinnus

Hanser-Verlag
ISBN 978-3-446-43438-7Visual C# 2012
Grundlagen und Profiwissen
Doberanz, Gewinnus

Hanser-Verlag
ISBN 978-3-446-43439-4


Softwareentwicklung mit C#

Hanspeter Mössenböck
dpunkt.Verlag
ISBN 3-89864-406-5


Visual C+ 2005
Günter Born, Benjamin Born
Entwickler.press
ISBN 978-3-939084-40-2


Visual C# 2008 von Andreas Kuehnel
Das umfassende Handbuch
Buch: Visual C# 2008


Visual C# 2008
geb., mit DVD
1.366 S., 49,90 Euro
Galileo Computing
ISBN 978-3-8362-1172-7


Datenbank-Programmierung mit Visual C# 2008
Walter Doberanz, Thomas Gewinnus
Microsoft Press
ISBN 978-3-86645-421-7


Handbuch der .NET-Programmierung
Rolf Wenger
Microsoft Press Deutschland
1. Auflage, 2007, 1664 Seiten
ISBN: 3866454198

Visual C# 2008
Andreas Kühnel
Galileo Computing
1366 S., 4., Auflage 2008, geb., mit DVD
49,90 Euro, ISBN 978-3-8362-1172-7

Links
http://www.guidetocsharp.de

http://msdn.microsoft.com/de-de/library/kx37x362.aspx

http://www.java2s.com/Code/CSharp/CatalogCSharp.htm .net Komponten
http://www.componentone.com/

http://www.componentone.com/SuperProducts/FlexGridWinForms/

http://www.devexpress.com/Index.xml

http://www.devexpress.com/Products/NET/Controls/WinForms/Grid/