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
MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ?MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ? par ROMELARD Fabrice
Formation initiale Durant la formation, le découpage classique est le suivant (je donnerai les équivalences Suisse lorsque je les connaîtrais) : Ecole primaire jusqu'au Collège : Formation générale permettant d'obtenir les méthodes...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice Y'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENTY'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENT par Aleks
Quand on a ce genre d'erreur sans log :
Et bas on a juste envie de choper le gas de Microsoft qu'a développé ça et lui foutre des baffes de Coboye ! ...
Cliquez pour lire la suite de l'article par Aleks [HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL[HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL par Pierrick CATRO-BROUILLET
Avec la sortie prochaine de la Beta Consumer Preview de Windows 8, j'avais envie de revenir sur une des fonctionnalités que j'attends le plus et que, en bon geek que je suis, j'utilise déjà : Hyper-V 3 ainsi son module PowerShell.
Il y a déjà pléthor...
Cliquez pour lire la suite de l'article par Pierrick CATRO-BROUILLET IIS7 - COMPRESSION GZIPIIS7 - COMPRESSION GZIP par cyril
La compression GZIP permet d'améliorer les performances de navigation en compressant ce qu'envoie le serveur à un client. Pour comprendre comment cela fonctionne, regardons ce qu'il se passe au niveau HTTP lorsqu'un client tente d'accéder à une ress...
Cliquez pour lire la suite de l'article par cyril SHAREPOINT 15 TECHNICAL PREVIEW MANAGED OBJECT MODEL SOFTWARE DEVELOPMENT KITSHAREPOINT 15 TECHNICAL PREVIEW MANAGED OBJECT MODEL SOFTWARE DEVELOPMENT KIT par Matthew
http://www.microsoft.com/download/en/details.aspx?id=28768&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+MicrosoftDownloadCenter+(Microsoft+Download+Center) ...
Cliquez pour lire la suite de l'article par Matthew
Logiciels
Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning Academy System (17.1.3.0)ACADEMY SYSTEM (17.1.3.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|