begin process at 2010 02 10 12:11:37
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Fichiers / Disque

 > RICHTEXTBOX NUMÉROTÉ (NUMÉROS DE LIGNES)

RICHTEXTBOX NUMÉROTÉ (NUMÉROS DE LIGNES)


 Information sur la source

Note :
Aucune note
Catégorie :Fichiers / Disque Source .NET ( DotNet ) Classé sous :RichTextBox, Text, Numérotation, Numéro, Ligne Niveau :Débutant Date de création :03/07/2009 Date de mise à jour :07/07/2009 09:58:47 Vu / téléchargé :2 022 / 152

Auteur : jray

Ecrire un message privé
Site perso
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note

 Description

Cliquez pour voir la capture en taille normale
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.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

07 juillet 2009 09:58:49 :
Problème d'upload => nouvelle tentative

 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) POST-TRAITEMENT NMEA/GPS: FILTRAGE DES POINTS, EXPORT KML/GP...

 Sources de la même categorie

Source avec Zip PILOTER WORD VIA MICROSOFT.OFFICE.INTEROP.WORD par whismeril
Source avec Zip PILOTER EXCEL VIA MICROSOFT.OFFICE.INTEROP.EXCEL par whismeril
Source avec Zip Source .NET (Dotnet) CHECK IDENTICAL FILES par eldim
Source avec Zip Source avec une capture SURVEILLER FICHIERS CRÉÉS AVEC FILESYSTEMWATCHER AMÉLIORÉ par TheOnlyMaX
Source avec Zip Source avec une capture Source .NET (Dotnet) MACPURGE (NOUVEAUX ALGOS POUR LES FICHIERS ... MADE IN MAC) par SwitchApocalyps

 Sources en rapport avec celle ci

Source avec Zip Source .NET (Dotnet) UN RICHTEXTBOX À PARTIR D'UN MEMORYSTREAM par Robert33
Source avec Zip Source avec une capture Source .NET (Dotnet) LECTURE LIGNE PAR LIGNE DE LA SORTIE STANDARD D'UN PROGRAMME... par SharpMao
Source avec Zip Source avec une capture Source .NET (Dotnet) COMPOSANT TEXTE RTF GÉRANT L'AJOUT ET LA SUPPRESSION DE MISE... par francknetjava
Source avec Zip Source .NET (Dotnet) SIMULER UNE SAISIE CLAVIER VERS UNE AUTRE APPLICATION par Nikoui
Source avec Zip Source avec une capture Source .NET (Dotnet) AFFICHER LE NUMÉRO DES LIGNES D'UN RICHTEXTBOX par sebmafate

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


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


Nos sponsors


Sondage...

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,061 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales