How to insert a Symbol (Pound, Euro, Copyright) into a Textbox

前端 未结 2 398
感动是毒
感动是毒 2020-12-09 04:42

I can use the Alt Key with the Number Pad to type symbols, but how do I programmatically insert a Symbol (Pound, Euro, Copyright) into a Textbox?

I have a

相关标签:
2条回答
  • 2020-12-09 05:03

    In C#, the Unicode character literal \uXXXX where the X's are hex characters will let you specify Unicode characters. For example:

    • \u00A3 is the Pound sign, £.
    • \u20AC is the Euro sign, €.
    • \u00A9 is the copyright symbol, ©.

    You can use these Unicode character literals just like any other character in a string.

    For example, "15 \u00A3 per item" would be the string "15 £ per item".

    You can put such a string in a textbox just like you would with any other string.

    Note: You can also just copy (Ctrl+C) a symbol off of a website, like Wikipedia (Pound sign), and then paste (Ctrl+V) it directly into a string literal in your C# source code file. C# source code files use Unicode natively. This approach completely relieves you from ever even having to know the four hex digits for the symbol you want.

    To parallel the example above, you could make the same string literal as simply "15 £ per item".

    Edit: If you want to dynamically create the Unicode character from its hex string, you can use this:

    public static char HexToChar(string hex)
    {
        return (char)ushort.Parse(hex, System.Globalization.NumberStyles.HexNumber);
    }
    

    For example, HexToChar("20AC") will get you the Euro sign.

    If you want to do the opposite operation dynamically:

    public static string CharToHex(char c)
    {
        return ((ushort)c).ToString("X4");
    }
    

    For example CharToHex('€') will get you "20AC".

    The choice of ushort corresponds to the range of possible char values, shown here.

    0 讨论(0)
  • 2020-12-09 05:03

    I cant believe this was difficult to find on the internet!

    For future developers,if you have the unicode character its easy to do. eg:

    C#:

    var selectionIndex = txt.SelectionStart;
    
    string copyrightUnicode = "00A9";
    int value = int.Parse(copyrightUnicode, System.Globalization.NumberStyles.HexNumber);
    string symbol = char.ConvertFromUtf32(value).ToString();
    
    txt.Text = txt.Text.Insert(selectionIndex, symbol);
    txt.SelectionStart = selectionIndex + symbol.Length;
    

    VB.Net

    Dim selectionIndex = txt.SelectionStart
    
    Dim copyrightUnicode As String = "00A9"
    Dim value As Integer = Integer.Parse(copyrightUnicode, System.Globalization.NumberStyles.HexNumber)
    Dim symbol As String = Char.ConvertFromUtf32(value).ToString()
    
    txt.Text = txt.Text.Insert(selectionIndex, symbol)
    txt.SelectionStart = selectionIndex + symbol.Length
    
    0 讨论(0)
提交回复
热议问题