Accueil > > > RICHTEXTBOX NUMÉROTÉ (NUMÉROS DE LIGNES)
RICHTEXTBOX NUMÉROTÉ (NUMÉROS DE LIGNES)
Information sur la source
Description
Ce code est un exemple de ce que j'utilise pour un éditeur de fichiers que j'ai développé. Lorsque le format est reconnu, il est affiché en colonnes dans une grille (contrôle "SourceGrid"), dans les autres cas, le contenu du fichier est simplement chargé sous forme de text ASCI dans un RichTextBox. Afin de mieux ressembler à un éditeur de texte universel genre PSPad ou UltraEdit, mais surtout permettre de retrouver des informations par exemple selon les détails d'un fichier log, j'ai voulu afficher les numéros de lignes à gauche du texte. Voici ma solution. Note: étant donné que je développe en anglais au boulot, ici j'ai procédé de la même manière: les contrôles, variables et commentaires sont en anglais. Mais je ne crois pas que ce soit très compliqué et vous pouvez toujours me poser des questions via les commentaires ci-dessous. (Merci de ne pas me demander des développements personnalisés par MP !!)
Source
- /*
- * Numerated RichTextBox
- * Développé par Jérôme Ray le 03.07.2009
- * Basé sur le code de Petr Minarik: http://www.codeproject.com/KB/edit/numberedtextbox.aspx
- *
- * Ce code peut être réutilisé librement dans n'importe que projet, commercial ou non
- * */
-
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
-
- namespace NumRichTextBox
- {
- public partial class TextEditor : Form
- {
- public TextEditor()
- {
- InitializeComponent();
-
- SetStyle(ControlStyles.UserPaint, true);
- SetStyle(ControlStyles.AllPaintingInWmPaint, true);
- SetStyle(ControlStyles.DoubleBuffer, true);
- SetStyle(ControlStyles.ResizeRedraw, true);
- }
-
- public void OpenFile(string filename)
- {
- try
- {
- // Load specified file in the RichTextBox
- this.richTextBox.LoadFile(filename, RichTextBoxStreamType.PlainText);
- }
- catch (Exception)
- {
- // Display error message
- MessageBox.Show("Unable to open specified file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
- // Close window
- this.Close();
- }
-
- }
-
- private void DrawLines(Graphics g, int firstLine)
- {
- // Number of text lines
- int linesCount = richTextBox.Lines.Length;
-
- // Last visible line (used to determine numbers panel width)
- int lastChar = this.richTextBox.GetCharIndexFromPosition(new Point(this.richTextBox.ClientRectangle.Width, this.richTextBox.ClientRectangle.Height));
- int lastLine = this.richTextBox.GetLineFromCharIndex(lastChar);
-
- // Line numbers layout (position, width)
- int rightMargin = 2, leftMargin = 5, topMargin = 2, bottomMargin = 15, verticalMargin = 2;
- SizeF maxTextSize = g.MeasureString(new string((char)48, lastLine.ToString().Length), this.richTextBox.Font);
- this.panelNum.Width = (int)maxTextSize.Width + leftMargin + rightMargin;
-
- // Clear existing numbers
- g.Clear(this.panelNum.BackColor);
-
- // First line name
- int lineNumber = firstLine + 1;
-
- // Y position for first line number
- int firstLineY = this.richTextBox.GetPositionFromCharIndex(this.richTextBox.GetFirstCharIndexFromLine(firstLine)).Y;
- int lineY = topMargin + firstLineY;
-
- // Write all visible line numbers
- while (true)
- {
- // Draw line number string
- string lineNumberLabel = lineNumber.ToString().PadLeft(lastLine.ToString().Length);
- g.DrawString(lineNumberLabel, this.richTextBox.Font, Brushes.Black, leftMargin, lineY);
-
- // Next line
- lineNumber += 1;
- lineY += Font.Height + verticalMargin;
-
- // End of numeration if and of text content or end of RichTextBox height
- if (lineY > ClientRectangle.Height - bottomMargin || lineNumber > linesCount)
- break;
- }
- }
-
- private void panelNum_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
- {
- // Update the line numbers
- int firstChar = this.richTextBox.GetCharIndexFromPosition(new Point(0, 0));
- int firstLine = this.richTextBox.GetLineFromCharIndex(firstChar);
-
- DrawLines(e.Graphics, firstLine);
- }
-
- private void richTextBox_SelectionChanged(object sender, System.EventArgs e)
- {
- this.panelNum.Invalidate(); // Request repaint => line numbers update
- }
-
- private void richTextBox_VScroll(object sender, System.EventArgs e)
- {
- this.panelNum.Invalidate(); // Request repaint => line numbers update
- }
-
- private void TextEditor_Load(object sender, EventArgs e)
- {
- // Required properties
- this.richTextBox.ScrollBars = RichTextBoxScrollBars.Both;
- this.richTextBox.WordWrap = false;
-
- // Required events
- this.richTextBox.SelectionChanged += new System.EventHandler(this.richTextBox_SelectionChanged);
- this.richTextBox.VScroll += new System.EventHandler(this.richTextBox_VScroll);
- this.panelNum.Paint += new PaintEventHandler(this.panelNum_Paint);
- }
-
- }
- }
/*
* Numerated RichTextBox
* Développé par Jérôme Ray le 03.07.2009
* Basé sur le code de Petr Minarik: http://www.codeproject.com/KB/edit/numberedtextbox.aspx
*
* Ce code peut être réutilisé librement dans n'importe que projet, commercial ou non
* */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace NumRichTextBox
{
public partial class TextEditor : Form
{
public TextEditor()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
}
public void OpenFile(string filename)
{
try
{
// Load specified file in the RichTextBox
this.richTextBox.LoadFile(filename, RichTextBoxStreamType.PlainText);
}
catch (Exception)
{
// Display error message
MessageBox.Show("Unable to open specified file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Close window
this.Close();
}
}
private void DrawLines(Graphics g, int firstLine)
{
// Number of text lines
int linesCount = richTextBox.Lines.Length;
// Last visible line (used to determine numbers panel width)
int lastChar = this.richTextBox.GetCharIndexFromPosition(new Point(this.richTextBox.ClientRectangle.Width, this.richTextBox.ClientRectangle.Height));
int lastLine = this.richTextBox.GetLineFromCharIndex(lastChar);
// Line numbers layout (position, width)
int rightMargin = 2, leftMargin = 5, topMargin = 2, bottomMargin = 15, verticalMargin = 2;
SizeF maxTextSize = g.MeasureString(new string((char)48, lastLine.ToString().Length), this.richTextBox.Font);
this.panelNum.Width = (int)maxTextSize.Width + leftMargin + rightMargin;
// Clear existing numbers
g.Clear(this.panelNum.BackColor);
// First line name
int lineNumber = firstLine + 1;
// Y position for first line number
int firstLineY = this.richTextBox.GetPositionFromCharIndex(this.richTextBox.GetFirstCharIndexFromLine(firstLine)).Y;
int lineY = topMargin + firstLineY;
// Write all visible line numbers
while (true)
{
// Draw line number string
string lineNumberLabel = lineNumber.ToString().PadLeft(lastLine.ToString().Length);
g.DrawString(lineNumberLabel, this.richTextBox.Font, Brushes.Black, leftMargin, lineY);
// Next line
lineNumber += 1;
lineY += Font.Height + verticalMargin;
// End of numeration if and of text content or end of RichTextBox height
if (lineY > ClientRectangle.Height - bottomMargin || lineNumber > linesCount)
break;
}
}
private void panelNum_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
// Update the line numbers
int firstChar = this.richTextBox.GetCharIndexFromPosition(new Point(0, 0));
int firstLine = this.richTextBox.GetLineFromCharIndex(firstChar);
DrawLines(e.Graphics, firstLine);
}
private void richTextBox_SelectionChanged(object sender, System.EventArgs e)
{
this.panelNum.Invalidate(); // Request repaint => line numbers update
}
private void richTextBox_VScroll(object sender, System.EventArgs e)
{
this.panelNum.Invalidate(); // Request repaint => line numbers update
}
private void TextEditor_Load(object sender, EventArgs e)
{
// Required properties
this.richTextBox.ScrollBars = RichTextBoxScrollBars.Both;
this.richTextBox.WordWrap = false;
// Required events
this.richTextBox.SelectionChanged += new System.EventHandler(this.richTextBox_SelectionChanged);
this.richTextBox.VScroll += new System.EventHandler(this.richTextBox_VScroll);
this.panelNum.Paint += new PaintEventHandler(this.panelNum_Paint);
}
}
}
Conclusion
Dans mon cas une feuille "child" MDI est uniquement constituée du texte (RichTextBox) et des numéros de lignes (Panel). Mais on peut bien sûr modifier ou ajouter des éléments. Une solution "de luxe" pourrait aussi être de créer un UserControl.
Historique
- 07 juillet 2009 09:58:49 :
- Problème d'upload => nouvelle tentative
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
RichTextbox numéro de ligne [ par Fildomen ]
Salutil y a pas une propriété à activer pour que le richtextbox affiche à droite une barre où afficher les numéros de ligne.merci
RichTextBox Sans limites [ par ricklekebekoi ]
Bonjour,Voilà, même après avoir choisis l'option "both" ou "ForcedBoth" de mon richtextbox pour les scrollbar, il refuse catéforiquement de continuer
couleur dans le richtextbox [ par Fildomen ]
salutj'ai un problème avec mon rtb, c'est que quand je colorie une partie du texte, et que je veux modifier une autre, la couleur de la première redev
Telephone - Modem [ par neoTHGLF ]
Bonjour, je programme actuellement un logiciel qui nécessite l'utilisation d'un modem analogique.Je voudrais en fait le modem en mode "attente" et que
SelectedText dans un richtextbox [ par kiboumz ]
Bonjour,j'essaie de faire dans mon programme une fonction de recherche qui sélectionne (highlight), dans le richtextbox, le texte recherché, mais je n
[RichTextBox]Recuperation de la ligne et de la colonne en cours [ par ip2x ]
Bonjour, je developpe un "parser" XML a l'aide d'une RichTextBox et je voudrais, pour des soucis d'ergonomie, afficher la position du curseur (Ligne,
richtextbox et taille de police [ par babe59 ]
Bonjour,Pourriez vous me dire pourquoi les lignes suivantes ne change pas la police (passage à une taille de 18) pour la seconde ligne du richtextbox
[C#][CF 1.1] Comment connaitre un numéro de ligne de fichier et y retourner ? [ par foolsky ]
Voila je vais lire un texte ligne par ligne j'ais créé une variable qui compte les ligne et qui s'incrémente donc a chaque ligne. Mais existe-t-il une
Inserer du text RTF dans RichTextBox [ par watcha2020 ]
Bonjour à tous, je cherche tout simplement à inserer du texte au format Rtf à la fin d'une RichTextBox.j'arrive tres bien à inserer mais je n'arrive p
Comparer des fichier text c# [ par imsse ]
Bonjour, dans le cadre d'une application web jai besoin d'historiser mes fichiers et de comparer le contenu de ces fichier différents . Ce sont des f
|
Derniers Blogs
[WP7] UTILISER UN WRAPPANEL DANS UNE APPLICATION WINDOWS PHONE 7[WP7] UTILISER UN WRAPPANEL DANS UNE APPLICATION WINDOWS PHONE 7 par Audrey
Lors de la réalisation de ma 2ème application Windows Phone 7, j'ai souhaité utiliser un WrapPanel pour afficher plusieurs photos. Mais le contrôle WrapPanel ne fait pas parti de la liste des contrôles inclus dans le SDK de la version Beta des outils pour...
Cliquez pour lire la suite de l'article par Audrey [WP7] BESOIN D'AVOIR DES DONNéES EN CACHE[WP7] BESOIN D'AVOIR DES DONNéES EN CACHE par Nicolas
Les développeurs ASP.NET ont l'habitude de mettre des données en cache pour éviter de requêter a chaque fois la base de données. Et il est toujours utilie de penser que vos utilisateurs mobiles n'ont pas troujours une super connexion 3G/WIFI et un for...
Cliquez pour lire la suite de l'article par Nicolas [TFS] COMMENT FORCER LA SAISIE D'UN AREA OU ITERATION[TFS] COMMENT FORCER LA SAISIE D'UN AREA OU ITERATION par cyril
Lorsque l'on créé un Work Item dans TFS, il est possible de le classer dans un "area" et dans une "iteration". Dans la plupart des types de projet, un "area" correspond à une catégorie, une "iteration" à un numéro de version. Il est possible de cré...
Cliquez pour lire la suite de l'article par cyril SQL : FONCTIONS D'AGRéGATION MIN/MAX ET VALEURS NULLSQL : FONCTIONS D'AGRéGATION MIN/MAX ET VALEURS NULL par coq
Les fonctions d'agrégation comme MIN et MAX ignorent les valeurs NULL présentes dans le jeu de données sur lequel porte leur calcul, d'où le fameux message d'avertissement : Warning: Null value is eliminated by an aggregate or other SET operation...
Cliquez pour lire la suite de l'article par coq VOTEZ POUR WARNYGOVOTEZ POUR WARNYGO par Nicolas
La vidéo du projet Warnygo est disponible sur facebook et attend vos votes ! Pour rappel: Warnygo est une application Windows Phone 7 qui permet d'alerter tous utilisateurs inscrits qui se trouve dans la zone où se passe l'...
Cliquez pour lire la suite de l'article par Nicolas
Logiciels
sDEVIS-FACTURES vlPRO (3.8.0)SDEVIS-FACTURES VLPRO (3.8.0)sDEVIS-FACTURES vlPRO a été mis au point pour permettre besoins des particuliers, créateurs, entr... Cliquez pour télécharger sDEVIS-FACTURES vlPRO LettresFaciles (5.6.0)LETTRESFACILES (5.6.0)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles MyPlanning 2010 (5.6.0)MYPLANNING 2010 (5.6.0)MyPlanning 2010 permet de créer des plannings sous la représentation de diagrammes. Plannings pré... Cliquez pour télécharger MyPlanning 2010 Emicsoft Mac DVD en iPad Convertisseur (3.1.16)EMICSOFT MAC DVD EN IPAD CONVERTISSEUR (3.1.16)Emicsoft Mac DVD en iPad Convertisseur, logiciel professionnel de convertir les fichiers DVD en i... Cliquez pour télécharger Emicsoft Mac DVD en iPad Convertisseur Emicsoft ipad ménager pour mac (3.1.08)EMICSOFT IPAD MéNAGER POUR MAC (3.1.08)Emicsoft ipad ménager pour mac est spécialement conçu pour les utilisateurs Mac pour copier des f... Cliquez pour télécharger Emicsoft ipad ménager pour mac
|