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
TECHDAYS PARIS 2010 : PLEINIèRE DERNIER JOURTECHDAYS PARIS 2010 : PLEINIèRE DERNIER JOUR par ROMELARD Fabrice
Cette session est la dernière pleinière de ces 3 jours de TechDays Paris 2010. Généralement, cette troisième journée est plus axée sur l'avenir vu par Microsoft. Après un retour sur l'avenir vu par la Science Fiction ou par ...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|