Feedback

C# - Sonderzeichen Klasse(n)

Veröffentlicht von am 5/4/2013
(1 Bewertungen)
Mit Hilfe dieser Klassen kann man in seinen Strings (MessageBoxen etc.) einfache Unicode-Entsprechungen für Sonderzeichen wie (c) anstatt © verwenden.
Die erste Klasse (Symbols) ist die Basis für die beiden Anderen. Ohne die Läuft garnichts.

Erste Klasse (Symbols):
Sie bietet mehrere Möglichkeiten diese zu verwenden.
1:
MessageBox.Show(Symbols.SymbolString("(c) 2013 Darius Arnold"));

2:
MessageBox.Show(Symbols.Copyright + " 2013 Darius Arnold")

3:
MessageBox.Show(Symbols.Symbol["(c)"] + " 2013 Darius Arnold")

4:
MessageBox.Show("(c) 2013 Darius Arnold".ToSymbolString());

(5:) // Eher umständlich
string copyright;
Symbols.Symbol.TryReadValue("(c)", out copyright);
MessageBox.Show(copyright + " 2013 Darius Arnold");


Die Klasse benutzt die ReplaceWithDictionary()-Methode aus dem folgenden Artikel:
http://dotnet-snippets.de/snippet/replace-mit-dictionary/1711

Die Klasse kann selbstverständlich erweitert werden.

Edit:
Mit der letzten (und neuen) Methode kann man jetzt auch zur Laufzeit Symbole hinzufügen.
Beispieldatei (symbols.txt):
(1)=❶
(2)=❷
(3)=❸
(4)=❹
(5)=❺

Einlesen:
Symbols.ReadSymbols("symbols.txt", "=");


Zweite Klasse (AutoSymbols):
Von dieser Klasse muss lediglich eine Instanz erstellt werden, um für die übergebenen Steuerelemente den "Autosymbol-Effekt" zu aktivieren. Selbstverständlich gibt es zusätzliche TextBox-Unterstützung (Wegen des Cursors).
Bei aktiviertem Effekt, werden, wenn sich der Text ändert, hinzugekommene Unicode-Entsprechungen für Sonderzeichen automatisch umgewandelt.

Verwendung:
AutoSymbols as = new AutoSymbols(myTextBox);


Die Klasse benutzt die CountOf()-Methode aus dem folgenden Artikel:
http://dotnet-snippets.de/snippet/vorkommen-eines-strings-in-einem-anderen-zaehlen/1713

Die Klasse ist selbstverständlich verbesserungsfähig. (Schreibt Vorschläge in die Kommis ;D)

Edit: Jetzt auch RichTextBox-Unterstützung und Fehlerbehebung.

Dritte Klasse (SymbolMessageBox):
Da der "Auto-Symbol-Effekt" nicht direkt für MessageBoxen Aktiviert werden kann, gibt es eine entsprechende Hilfsklasse für diese. Aufruf wie bei der "normalen" MessageBox. (Es wurden nicht alle Überladungen übernommen.):
SymbolMessageBox.Show("(c) 2013 Darius Arnold");


Die Klasse kombiniert die WinForms-Methode MessageBox.Show() mit der ToSymbolString()-Methode aus der Symbols-Klasse.

Der Trick:
Alle Klassen bauen auf die erste Klasse auf. Werden dort manuell Symbole hinzugefügt oder welche geladen, werden auch die neuen Symbole von ALLEN Klassen unterstützt.

Information:
Das "© 2013 Darius Arnold" ist natürlich nur ein Beispiel, weil da das Copyright-Zeichen drin ist. Ihr dürft die Klasse natürlich Frei benutzen: Auch Kommerziell, ohne Namensnennung - Ist ja nichts großartiges.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DariusArnold
{
    /// <summary>
    /// Class with Methods and Variables for the easy using of symbols.
    /// </summary>
    static class Symbols
    {
        /// <summary>
        ///
        /// </summary>
        public const string Trademark = "™";
        /// <summary>
        ///
        /// </summary>
        public const string Omega = "Ω";
        /// <summary>
        ///
        /// </summary>
        public const string Summation = "∑";
        /// <summary>
        ///
        /// </summary>
        public const string ArrowRight = "→";
        /// <summary>
        ///
        /// </summary>
        public const string Squareroot = "√";
        /// <summary>
        /// ©
        /// </summary>
        public const string Copyright = "©";
        /// <summary>
        /// ®
        /// </summary>
        public const string Registered = "®";
        /// <summary>
        ///
        /// </summary>
        public const string CircleBlack = "●";
        /// <summary>
        ///
        /// </summary>
        public const string CircleWhite = "○";
        /// <summary>
        ///
        /// </summary>
        public const string SquareWhite = "□";

        /// <summary>
        /// Dictionary with the Symbols.
        /// </summary>
        public static readonly Dictionary<String, String> Symbol = new Dictionary<string, string> {
        {"(tm)", "™"},
        {"(o)", "Ω"},
        {"(sum)", "∑"},
        {"->", "→"},
        {"(sr)", "√"},
        {"(c)", "©"},
        {"(r)", "®"},
        {"(cb)", "●"},
        {"(cw)", "○"},
        {"(sw)", "□"}
        };

        /// <summary>
        /// Replaces the unicode signs with the matching symbols.
        /// </summary>
        /// <param name="input">The text whitch should be edited.</param>
        /// <returns>The edited string.</returns>
        public static string SymbolString(string input)
        {
            return ReplaceWithDictionary(input, Symbol);
        }

        /// <summary>
        /// Replaces each occurrence of a key of a dictionary in a string with the maching value.
        /// </summary>
        /// <param name="input">The text which should be edited.</param>
        /// <param name="dict">The dictionary with the strings.</param>
        /// <returns>The edited string.</returns>
        private static string ReplaceWithDictionary(string input, Dictionary<String, String> dict)
        {
            string output = input;
            foreach (string s in dict.Keys)
                output = output.Replace(s, dict[s]);

            return output;
        }

        /// <summary>
        /// Opens a unicode file - not ANSI - and reads Symbols and their unicode matches. First the match, second the symbol.
        /// </summary>
        /// <param name="FileName">The file with the symbols.</param>
        /// <param name="Seperator">The seperator, which splits the symbols and the matchs.</param>
        public static void ReadSymbols(string FileName, string Seperator)
        {
            string[] splitString = { Seperator };
            if (System.IO.File.Exists(FileName))
            {
                bool addedAll = true;
                foreach (string line in System.IO.File.ReadAllLines(FileName))
                {
                    try
                    {
                        Symbol.Add(line.Split(splitString, StringSplitOptions.RemoveEmptyEntries)[0], line.Split(splitString, StringSplitOptions.RemoveEmptyEntries)[1]);
                    }
                    catch
                    {
                        addedAll = false;
                    }
                }
                if (!addedAll)
                    throw new Exception("Didn't add all symbols.");
            }
            else
                throw new System.IO.FileNotFoundException("The file does not exist.");
        }

        /// <summary>
        /// Converts all symbol matches in this string into Symbols.
        /// </summary>
        /// <param name="str">The input string.</param>
        /// <returns>The new string.</returns>
        public static string ToSymbolString(this string str)
        {
            return Symbols.SymbolString(str);
        }
    }


    /// <summary>
    /// Create a new instance to set all symbols in the text property of all selected items automaticly.
    /// </summary>
    class AutoSymbols
    {
        /// <summary>
        /// Activates the automatic symbol system for the controls.
        /// </summary>
        /// <param name="controls">The controls, which the system should be activated for.</param>
        public AutoSymbols(List<Control> controls)
        {
            foreach (Control c in controls)
                c.TextChanged += new EventHandler(SetSymbols);
        }

        /// <summary>
        /// Activates the automatic symbol system for the control.
        /// </summary>
        /// <param name="controls">The control, which the system should be activated for.</param>
        public AutoSymbols(Control control)
        {
            AddControl(control);
        }

        public void AddControl(Control c)
        {
            c.TextChanged += new EventHandler(SetSymbols);
        }

        /// <summary>
        /// Puts all unicode signs into symbols.
        /// </summary>
        /// <param name="sender">The sender control (as object).</param>
        /// <param name="e">The EventArguments 'e'.</param>
        private void SetSymbols(object sender, EventArgs e)
        {
            Control c = (Control)sender;
            int cursor = -1;
            int minus = 0;
            TextBox tb = new TextBox();
            RichTextBox rtb = new RichTextBox();
            if (c is TextBox)
            {
                tb = (TextBox)sender;
                cursor = tb.SelectionStart;
                foreach (string s in Symbols.Symbol.Keys)
                    minus += CountOf(tb.Text, s) * (s.Length - 1);
            }
            else if (c is RichTextBox)
            {
                rtb = (RichTextBox)sender;
                cursor = rtb.SelectionStart;
                foreach (string s in Symbols.Symbol.Keys)
                    minus += CountOf(rtb.Text, s) * (s.Length - 1);
            }

            c.Text = Symbols.SymbolString(c.Text);

            if (cursor != -1)
            {
                tb.SelectionStart = cursor - minus;
                rtb.SelectionStart = cursor - minus;
            }
        }

        /// <summary>
        /// Counts how many times a strings appears in an other.
        /// </summary>
        /// <param name="input">The String which contains the other.</param>
        /// <param name="sub">The string which should be counted.</param>
        /// <returns>The count of the string as integer.</returns>
        private int CountOf(string input, string substring)
        {
            string[] seperator = { substring };
            int count = 0;
            try
            {
                count = input.Split(seperator, StringSplitOptions.None).Count() - 1;
            }
            catch
            {
            }
            return count;
        }
    }

    /// <summary>
    /// Alternative class to the default MessageBox, which supports the symbol mactches.
    /// </summary>
    static class SymbolMessageBox
    {
        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text)
        {
            return MessageBox.Show(text.ToSymbolString());
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString());
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons);
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons, icon);
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons, icon, defaultButton);
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons, icon, defaultButton, options);
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool displayHelpButton)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons, icon, defaultButton, options, displayHelpButton);
        }

        /// <summary>
        /// Shows a SymbolMessageBox.
        /// </summary>
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator)
        {
            return MessageBox.Show(text.ToSymbolString(), caption.ToSymbolString(), buttons, icon, defaultButton, options, helpFilePath, navigator);
        }
    }
}
Abgelegt unter Sonderzeichen, Symbole, Symbols, Ersetzen, Replace.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!