IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Aide pour mettre en couleur du text.


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    44
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 44
    Par défaut Aide pour mettre en couleur du text.
    Bonjour,
    J'ai créé un code qui crée du rtf pour pouvoir mettre en couleur du texte, mais il ne fonctionne pas... alors je me demmandais si il y aurait une autre façon de faire pour pourvoir mettre en couleur et changer le font de plusieurs partie d'une textbox.

    Voici le code que j'ai créé pour le rtf au cas ou...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Collections;
    using System.Drawing;
     
    namespace Highlighting
    {
        public class HighlightingTextBox : RichTextBox
        {
            private ArrayList HighlightDescriptors;
            private ArrayList Separators;
            private TableGenerator generator;
     
            public HighlightingTextBox() : base()
            {
                this.HighlightDescriptors = new ArrayList();
                this.Separators = new ArrayList();
                generator = new TableGenerator(Color.Blue, Font);
            }
            public void AddSeparator(char c)
            {
                AddSeparator("" + c);
            }
            public void AddSeparator(string s)
            {
                Separators.Add(s);
            }
            protected override void OnTextChanged(EventArgs e)
            { 
               base.OnTextChanged(e);
               Highlight();
            }
            public void Highlight()
            {
                //@"{\rtf1\ansi\ansicpg1255\deff0\deflang1037"
                string rtf = "";
                SetDefaultSettings(ref rtf);
                rtf += " ";
     
                string[] lines = Text.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Split('\n');
     
                for (int index = 0; index < lines.Length; index++)
                {
                    //if (index != 0) rtf += "\\par\n";
     
                    string line = lines[index];
                    string[] tokens = line.Split((string[])Separators.ToArray(typeof(string)), StringSplitOptions.None);
     
                    if (tokens.Length == 0)
                    {
                        rtf += lines[index];
                        continue;
                    }
                    int tokenCount = 0;
                    for (int i = 0; i < line.Length; )
                    {
                        char curChar = line[i];
                        if (isSeparator(line,i)!=0)
                        {
                            int sp = isSeparator(line, i);
                            rtf += line.Substring(i, sp);
                            i += sp;
                            continue;
                        }
                        if (tokenCount >= tokens.Length) break;
                        string curToken = tokens[tokenCount];
                        tokenCount++;
                        bool isAdded = false;
                        foreach (HighlightDescriptor h in HighlightDescriptors)
                        {
                            if (Match(h, curToken))
                            {
                                isAdded = true;
                                SetDescriptorSettings(ref rtf, h);
                                switch (h.DescriptorType)
                                {
                                    case DescriptorType.Word:
                                        rtf += line.Substring(i,curToken.Length);
                                        i += curToken.Length;
                                        break;
                                    case DescriptorType.ToEOL:
                                        rtf += GetWordBounsOnCharIndex(line, i, out i);
                                        break;
                                    case DescriptorType.ToEOW:
                                        rtf += line.Substring(i, line.Length);
                                        i = line.Length;
                                        break;
                                    case DescriptorType.ToCloseToken:
     
                                        int start = i+h.CloseToken.Length;
                                        while (line.IndexOf(h.CloseToken, start) == -1 && index < lines.Length)
                                        {
                                            rtf += line.Remove(0, i);
                                            index++;
                                            if (index < lines.Length)
                                            {
                                                rtf += "\\par\n";
                                                line = lines[index];
                                                i = start = 0;
                                            }
                                            else
                                            {
                                                i = start = line.Length;
                                            }
                                        }
                                        int idx = line.IndexOf(h.CloseToken, start);
                                        if (idx != -1)
                                        {
                                            rtf += line.Substring(i, idx + h.CloseToken.Length);
                                            line = line.Remove(0, idx + h.CloseToken.Length);
                                            tokenCount = 0;
                                            tokens = line.Split((string[])Separators.ToArray(typeof(string)), StringSplitOptions.None);
                                            i = 0;
                                        }
                                        break;
                                }
                                SetDefaultSettings(ref rtf);
                            }
                        }
                        if (!isAdded)
                        {
                            rtf += line.Substring(i, curToken.Length);
                            i += curToken.Length;
                        }
     
                    }
                    rtf += "\\par\n";
                }
     
                    rtf=@"{\rtf1\ansi\ansicpg1255\deff0\deflang1037" + generator.GenerateTables() + "\n"+@"\viewkind4\uc1\pard" + rtf + "}";
                    Rtf = rtf;
     
     
            }
     
            private string GetWordBounsOnCharIndex(string sText, int pCharIndex, out int curTokenEndIndex)
            {
                int curTokenStartIndex = LastIndexOfAny(sText,(string[])Separators.ToArray(), Math.Min(pCharIndex, sText.Length - 1)) + 1;
     
                //Now that we know where it starts, where does it end
                curTokenEndIndex = IndexOfAny(sText, (string[])Separators.ToArray(), curTokenStartIndex);
                //No end found, select all
                if (curTokenEndIndex == -1)
                    curTokenEndIndex = sText.Length;
                //now determin the selected word or token
                return sText.Substring(curTokenStartIndex, Math.Max(curTokenEndIndex - curTokenStartIndex, 0)).ToUpper();
            }
            private int IndexOfAny(string text, string[] separators, int startIndex)
            {
                foreach (string sep in separators)
                {
                    int offset = 0;
                    for (int i = startIndex; i <text.Length; i++)
                    {
                        if (text[i] == sep[offset])
                        {
                            offset++;
                            if (offset >= sep.Length)
                            {
                                return i;
                            }
                        }
                        else
                            offset = 0;
                    }
                }
                return -1;
            }
            private int LastIndexOfAny(string text, string[] separators, int startIndex)
            {
                foreach (string sep in separators)
                {
                    int offset = 0;
                    for (int i = text.Length; i >= startIndex; i--)
                    {
                        if (text[i] == sep[sep.Length - offset])
                        {
                            offset++;
                            if (offset >= sep.Length)
                            {
                                return i;
                            }
                        }
                        else
                            offset = 0;
                    }
                }
                return -1;
            }
            private int isSeparator(string line, int index)
            {
                for (int i = 0; i < Separators.Count; i++)
                {
                    string sep = (string)Separators[i];
                    if (line.Length <= index + sep.Length)
                    {
                        if (line.Substring(index , sep.Length) == sep)
                        {
                            return sep.Length;
                        }
                    }
                }
                return 0;
            }
            private bool Match(HighlightDescriptor h, string token)
            {
                switch (h.DescriptorRecognition)
                {
                    case DescriptorRecognition.WholeWord:
                        if (token == h.Token)
                        {
                            return true;
                        }
                        return false;
                    case DescriptorRecognition.StartsWith:
                        if (token.StartsWith(h.Token))
                        {
                            return true;
                        }
                        return false;
                    case DescriptorRecognition.Contains:
                        if (token.Contains(h.Token))
                        {
                            return true;
                        }
                        return false;
                    default: return false;
                }
            }
            private void SetDescriptorSettings(ref string str, HighlightDescriptor h)
            {
                SetColor(ref str, h.Color);
                SetFont(ref str, h.Font);
                SetFontSize(ref str, h.Font);
                str += " ";
            }
            private void SetDefaultSettings(ref string str)
            {
                SetColor(ref str, Color.Blue);
                SetFont(ref str, Font);
                SetFontSize(ref str, Font);
                str += " ";
     
            }
            private void SetColor(ref string rtf,Color c)
            {
                rtf += @"\cf" + generator.AddColor(c);
            }
            private void SetFont(ref string rtf, Font f)
            {
                rtf += @"\f" + generator.AddFont(f);
                if (f.Bold)
                    rtf += @"\b";
                if (f.Italic)
                    rtf += @"\i";
            }
            private void SetFontSize(ref string rtf, Font f)
            {
                rtf += @"\fs" + Math.Round((f.Size * 2));
            }    
        }
    }
    TableGenerator:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.Drawing;
     
    namespace Highlighting
    {
        class TableGenerator
        {
            private ArrayList colors;
            private ArrayList fonts;
     
            public TableGenerator(Color defaultColor, Font defaultFont)
            {
                colors = new ArrayList();
                fonts = new ArrayList();
     
                colors.Add(defaultColor);
                fonts.Add(defaultFont);
            }
            public int AddColor(Color c)
            {
                int i = At(c);
                if (i != -1)
                    return i+1;
                return colors.Add(c)+1;
            }
            private int At(Color c)
            {
                for (int i = 0; i < colors.Count;i++ )
                {
                    Color co = (Color)colors[i];
                    if (co.R == c.R && co.G == c.G && co.B == c.B)
                    {
                        return i;
                    }
                }
                return -1;
            }
     
            public int AddFont(Font f)
            {
                int i = At(f);
                if (i != -1)
                    return i;
                return fonts.Add(f);
            }
            private int At(Font f)
            {
                for (int i = 0; i < fonts.Count; i++)
                {
                    if (((Font)fonts[i]).Name == f.Name)
                    {
                        return i;
                    }
                }
                return -1;
            }
            public string GenerateTables()
            {
                return GenerateFontTable() + "\n" + GenerateColorTable();
            }
            private string GenerateFontTable()
            {
                string table = "{\\fonttbl\n";
                for (int i = 0; i < fonts.Count; i++)
                {
                    if (fonts[i] != null)
                    {
                        table += @"{\f" + i + @"\fnil\fcharset0 " + ((Font)fonts[i]).Name + ";}\n";
                    }
                }
     
                return table.Length > 9 ? table + "}" : "";
            }
            private string GenerateColorTable()
            {
                string table = "{\\colortbl ;";
                for (int i = 0; i < colors.Count; i++)
                {
                    if (colors[i] != null)
                    {
                        Color c = ((Color)colors[i]);
                        table += @"\red" + c.R + @"\green" + c.G + @"\blue" + c.B + ";";
                    }
                }
                return table.Length > 9 ? table + "}" : "";
            }
     
        }
    }
    HighlightDescriptor (ce n'est pas moi qui a créé ce code):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    using System;
    using System.Drawing;
     
    namespace Highlighting
    {
        public class HighlightDescriptor
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="HighlightDescriptor"/> class.
            /// </summary>
            /// <param name="token">The token.</param>
            /// <param name="color">The color.</param>
            /// <param name="font">The font.</param>
            /// <param name="descriptorType">Type of the descriptor.</param>
            /// <param name="dr">The dr.</param>
            /// <param name="useForAutoComplete">if set to <c>true</c> [use for auto complete].</param>
            public HighlightDescriptor(string token, Color color, Font font, DescriptorType descriptorType, DescriptorRecognition dr, bool useForAutoComplete)
            {
                if (descriptorType == DescriptorType.ToCloseToken)
                {
                    throw new ArgumentException("You may not choose ToCloseToken DescriptorType without specifing an end token.");
                }
                Color = color;
                Font = font;
                Token = token;
                DescriptorType = descriptorType;
                DescriptorRecognition = dr;
                CloseToken = null;
                UseForAutoComplete = useForAutoComplete;
            }
     
            /// <summary>
            /// Initializes a new instance of the <see cref="HighlightDescriptor"/> class.
            /// </summary>
            /// <param name="token">The token.</param>
            /// <param name="closeToken">The close token.</param>
            /// <param name="descriptorType">Type of the descriptor.</param>
            /// <param name="dr">The dr.</param>
            /// <param name="color">The color.</param>
            /// <param name="font">The font.</param>
            /// <param name="useForAutoComplete">if set to <c>true</c> [use for auto complete].</param>
            public HighlightDescriptor(string token, string closeToken, DescriptorType descriptorType, DescriptorRecognition dr, Color color, Font font, bool useForAutoComplete)
            {
                if (dr == DescriptorRecognition.RegEx)
                {
                    throw new ArgumentException("You may not choose RegEx DescriptorType with an end token.");
                }
                Color = color;
                Font = font;
                Token = token;
                DescriptorType = descriptorType;
                CloseToken = closeToken;
                DescriptorRecognition = dr;
                UseForAutoComplete = useForAutoComplete;
            }
     
            public readonly Color Color;
            public readonly Font Font;
            public readonly string Token;
            public readonly string CloseToken;
            public readonly DescriptorType DescriptorType;
            public readonly DescriptorRecognition DescriptorRecognition;
            public readonly bool UseForAutoComplete;
        }
     
     
        public enum DescriptorType
        {
            /// <summary>
            /// Causes the highlighting of a single word
            /// </summary>
            Word,
            /// <summary>
            /// Causes the entire line from this point on the be highlighted, regardless of other tokens
            /// </summary>
            ToEOL,
            /// <summary>
            /// Highlights all text until the end token;
            /// </summary>
            ToCloseToken,
            /// <summary>
            /// To end of word.
            /// </summary>
            ToEOW
     
        }
     
        public enum DescriptorRecognition
        {
            /// <summary>
            /// Only if the whole token is equal to the word
            /// </summary>
            WholeWord,
            /// <summary>
            /// If the word starts with the token
            /// </summary>
            StartsWith,
            /// <summary>
            /// If the word contains the Token
            /// </summary>
            Contains,
            /// <summary>
            /// the start token is a RegEx.
            /// Stoptoken is not used
            /// </summary>
            RegEx
        }
     
    }

  2. #2
    Membre très actif
    Homme Profil pro
    Inscrit en
    Septembre 2008
    Messages
    168
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations forums :
    Inscription : Septembre 2008
    Messages : 168
    Par défaut pourquoi t'as pas utilisé le ...
    colorDialog?
    si tu utilises visual studio, parmi les outils tu trouveras colorDialog
    je trouve cette classe très simple dans l'utilisation et presque tout y a été déjà fait!

  3. #3
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    44
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 44
    Par défaut
    Je veux coloré du texte (comme notepad++ par example) et non choisir une couleur dans un dialog...

    Edit: J'avais peur de perdre de la vitesse en utilisant la selection pour colorier, mais je vais essayé sa demain.

  4. #4
    Membre Expert Avatar de sisqo60
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Février 2006
    Messages
    754
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : Consultant informatique

    Informations forums :
    Inscription : Février 2006
    Messages : 754

  5. #5
    Membre averti
    Inscrit en
    Septembre 2008
    Messages
    44
    Détails du profil
    Informations forums :
    Inscription : Septembre 2008
    Messages : 44
    Par défaut
    Merci il en avait un ou deux que j'avais pas vu.
    J'ai utilisé ce code: http://www.codeproject.com/KB/edit/S...hlighting.aspx comme example pour faire le mien.

    Edit:

    Finalement j'ai décidé d'utiliser la sélection et les regex pour colorier et changer le font du texte.
    Voilà le code pour ceux que sa intéresse:
    HighlightText.cs:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Collections;
    using System.Text.RegularExpressions;
    using System.Runtime.InteropServices;
     
    namespace HighlightText
    {
     
        public class HighlightText : RichTextBox
        {
     
            [DllImport("user32.dll")] // import lockwindow to remove flashing
            public static extern bool LockWindowUpdate(IntPtr hWndLock);
     
            private char[] separators;
            private ArrayList descriptors;
     
            public HighlightText() : base()
            {
                descriptors = new ArrayList();
            }
            public void AddDescriptor(HighlighDescriptor h)
            {
                if (h != null)
                    descriptors.Add(h);
            }
            protected override void OnTextChanged(EventArgs e)
            {
                base.OnTextChanged(e);
                Highligh();
            }
     
            private void Highligh()
            {
                try
                {
                    LockWindowUpdate(base.Handle);
                    int startpos = SelectionStart;
                    SelectAll();
                    SelectionColor = ForeColor;
                    SelectionFont = Font;
                    ProcessRegex();
                    SelectionStart = startpos;
                    SelectionLength = 0;
                }
                finally { LockWindowUpdate(IntPtr.Zero); }
            }
            private void ProcessRegex()
            {
                foreach (HighlighDescriptor h in descriptors)
                {
                    Regex regex = new Regex(h.Regex);
                    foreach (Match m in regex.Matches(Text))
                    {
                        Select(m.Index, m.Length);
                        if(h.Color!=null)
                            SelectionColor = h.Color;
                        if(h.Font!=null)
                            SelectionFont = h.Font;
                        SelectionStart = m.Length + m.Index;
                        SelectionLength = 0;
                        SelectionColor = ForeColor;
                        SelectionFont = Font;
                    }
                }
            }
        }
    }
    HighlighDescriptor.cs:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Drawing;
     
    namespace HighlightText
    {
        public class HighlighDescriptor
        {
            public HighlighDescriptor(string regex, Color color, Font font)
            {
                Color = color;
                Font = font;
                Regex = regex;
            }
            public readonly Color Color;
            public readonly Font Font;
            public readonly string Regex;
        }
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Pb de selection de cellule pour mettre en couleur
    Par Dexor dans le forum Macros et VBA Excel
    Réponses: 7
    Dernier message: 24/08/2006, 16h47
  2. [VB6]Aide pour mettre format date avec inputbox
    Par Geliwy77 dans le forum VB 6 et antérieur
    Réponses: 13
    Dernier message: 28/01/2006, 20h13
  3. Réponses: 3
    Dernier message: 05/12/2005, 02h30
  4. Aide pour changer de couleur sur les primitifs GLUT
    Par romainhoarau2764 dans le forum GLUT
    Réponses: 3
    Dernier message: 19/03/2005, 13h30
  5. [débutant] Aide pour mettre une FOREIGN KEY sur une table
    Par cauldron dans le forum Langage SQL
    Réponses: 2
    Dernier message: 14/11/2004, 17h16

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo