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
    }
 
}