Richer RichTextBox (Part 2) - The Code Projec...

来源:百度文库 编辑:神马文学网 时间:2024/04/28 05:22:24
 
3,677,233 members and growing!   6,247 now online.txjchen |My Settings |My Bookmarks |My Articles |Sign out
HomeMFC/C++C#ASP.NET.NETVB.NETAll Topics  Help!ArticlesMessage BoardsStoreFrontLounge
All Topics,C#,.NET >>C# Controls >>Edit Controls
Richer RichTextBox (Part 2)
ByNikola Stepan.
An article on extending the RichTextBox class in C#.
C#
Windows, .NET (.NET 1.1)
Win32, VS (VS.NET2003)
Dev
Posted: 9 Nov 2005
Updated: 13 Jan 2006
Views: 19,547
Announcements
$10,000 worth of prizes to be wonMonthly Competition

Search   Articles Authors   Advanced Search
Sitemap |Add to IE Search
PrintBroken Article?BookmarkDiscussSend to a friend
5 votes for this article.
Popularity: 3.05. Rating: 4.36 out of 5.
You are signed up for one or morenewsletters but unfortunately we are unable to send you emails. Please clickhere to have an email sent that will allow us to confirm your email address.
Download demo installer - 305 KbDownload demo project - 8.02 KbDownload source - 0.8 Kb

Introduction
In thefirst part, we extended the RichTextBox class with methods that change the FontStyle of a selection without losing the styles that are currently present. Unfortunately, there are a few more features missing from the RichTextBox control that could potentially be useful in word-processor-like applications. These kinds of applications commonly use a status bar to display information about the current cursor position. In this part, we will enrich the RichTextBox control with functionality that can be used for that purpose.
Usage
When nothing is selected, we want to display line number, column number and cursor position. When some portion of text is selected, the status bar should display the start, end and length of the selection. Also, from the client perspective, those features should be self-documentary and easy to use.
Collapse
this.rtb.CursorPositionChanged += new System.EventHandler(this.rtb_CursorPositionChanged); this.rtb.SelectionChanged += new System.EventHandler(this.rtb_SelectionChanged); . . . private void rtb_CursorPositionChanged(object sender, System.EventArgs e) { int line = rtb.CurrentLine; int col = rtb.CurrentColumn; int pos = rtb.CurrentPosition; statusBar.Text = "Line " + line + ", Col " + col + ", Position " + pos; } private void rtb_SelectionChanged(object sender, System.EventArgs e) { int start = rtb.SelectionStart; int end = rtb.SelectionEnd; int length = rtb.SelectionLength; statusBar.Text = "Start " + start + ", End " + end + ", Length " + length; }
To achieve such behavior, we need to extend the RichTextBox class in the following manner:
Collapse
using System; using System.Drawing; using System.Windows.Forms; namespace Nik.UserControls { public class RicherTextBox2 : System.Windows.Forms.RichTextBox { public event EventHandler CursorPositionChanged; protected virtual void OnCursorPositionChanged( EventArgs e ) { if ( CursorPositionChanged != null ) CursorPositionChanged( this, e ); } protected override void OnSelectionChanged( EventArgs e ) { if ( SelectionLength == 0 ) OnCursorPositionChanged( e ); else base.OnSelectionChanged( e ); } public int CurrentColumn { get { return CursorPosition.Column( this, SelectionStart ); } } public int CurrentLine { get { return CursorPosition.Line( this, SelectionStart ); } } public int CurrentPosition { get { return this.SelectionStart; } } public int SelectionEnd { get { return SelectionStart + SelectionLength; } } } internal class CursorPosition { [System.Runtime.InteropServices.DllImport("user32")] public static extern int GetCaretPos(ref Point lpPoint); private static int GetCorrection(RichTextBox e, int index) { Point pt1 = Point.Empty; GetCaretPos(ref pt1); Point pt2 = e.GetPositionFromCharIndex(index); if ( pt1 != pt2 ) return 1; else return 0; } public static int Line( RichTextBox e, int index ) { int correction = GetCorrection( e, index ); return e.GetLineFromCharIndex( index ) - correction + 1; } public static int Column( RichTextBox e, int index1 ) { int correction = GetCorrection( e, index1 ); Point p = e.GetPositionFromCharIndex( index1 - correction ); if ( p.X == 1 ) return 1; p.X = 0; int index2 = e.GetCharIndexFromPosition( p ); int col = index1 - index2 + 1; return col; } } } Resources
Inheriting from a Windows Forms Control with Visual C#.CalcSharp support site.
Nikola Stepan
Clickhere to view Nikola Stepan‘s online profile.
Other popular C# Controls articles:
Themed Windows XP style Explorer Bar A fully customizable Windows XP style Explorer Bar that supports Windows XP themes and animated expand/collapse with transparency.
XPTable - .NET ListView meets Java‘s JTable A fully customisable ListView style control based on Java‘s JTable.
SourceGrid - Open Source C# Grid Control SourceGrid is a free open source grid control. Supports virtual grid, custom cells and editors, advanced formatting options and many others features
TaskbarNotifier, a skinnable MSN Messenger-like popup in C# and now in VB.NET too The TaskbarNotifier class allows to display an MSN Messenger-like animated popup with a skinned background
[Top] Rate this Article for us!     PoorExcellent


FAQ  Message score threshold 1.0 2.0 3.0 4.0 5.0    Search comments
View Normal (slow) Preview (slow) Message View Topic View Thread View Expanded (Supporters only)    Per page 10 25 50
New Message Msgs 1 to 4 of 4 (Total: 4) (Refresh) First Prev Next
Subject  Author  Date

 Finding Text Position  mark_e_mark  10:49 30 Mar ‘06
  Hi Nikola,
Great Article!
I was wondering if you have know of a way that I can extract the text from a RTB and find the position each char is in the display?
I know its a wierd thing to do but I really need to do it...
Regards
Mark
[Reply |Email |View Thread |Get Link] Score: 2.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Problem with column position  gijsvennix  7:29 2 Jan ‘06
  There seems to be a bug in the columnposition in the statusbar. It happens under the following conditions:
Turn off wordwrap on the rtb, type a line longer then the width so a horizontal scrollbar appears, scroll to the right. Now position the cursor somewhere on the line to see that the columnposition displayed is counted from the beginning of the visible part of the sentence. Not from the actual beginning of the sentence.
[Reply |Email |View Thread |Get Link] Score: 1.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Problem with column position  Nikola Stepan  9:46 13 Jan ‘06
  gijsvennix wrote:
There seems to be a bug in the columnposition in the statusbar. It happens under the following conditions:
Turn off wordwrap on the rtb, type a line longer then the width so a horizontal scrollbar appears, scroll to the right. Now position the cursor somewhere on the line to see that the columnposition displayed is counted from the beginning of the visible part of the sentence. Not from the actual beginning of the sentence.
I updated article and source code which should now work with both wordwrap on/off.
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Problem with column position  Ribeaucoup Thomas  4:05 14 Dec ‘06
  Greetings,
Thanks for the example!
I missed the function ‘GetLineFromCharIndex‘ in MSDN and it was exactly what I was looking for !
But I don‘t understand why you use point coordinates instead of using characters number calculation...
Moreover I don‘t understand the utility of the strange ‘GetCorrection‘ !
What about this much simpler and faster solution :
public int CurrentColumn
{
get
{
return SelectionStart - GetFirstCharIndexOfCurrentLine() + 1 ;
}
}
public int CurrentLine
{
get
{
return GetLineFromCharIndex( SelectionStart ) + 1 ;
}
}
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

Last Visit: 23:41 Wednesday 3rd January, 2007 First Prev Next
General comment   News / Info   Question   Answer   Joke / Game   Admin message
Updated: 13 Jan 2006 Article content copyright Nikola Stepan, 2005
everything else Copyright ©CodeProject, 1999-2006.
Web10 |Advertise on The Code Project |Privacy

The Ultimate Toolbox •ASP Alliance •Developer Fusion •Developersdex •DevGuru •Programmers Heaven •Planet Source Code •Tek-Tips Forums •
Help!
Articles
Message Boards
StoreFront
Lounge
What is ‘The Code Project‘?
General FAQ
Post a Question
Site Directory
About Us
Latest
Most Popular
Search
Site Directory
Submit an Article
Update an Article
Article Competition
Windows Vista
Visual C++
ATL / WTL / STL
COM
C++/CLI
C#
ASP.NET
VB.NET
Web Development
.NET Framework
Mobile Development
SQL / ADO / ADO.NET
XML / XSL
OS / SysAdmin
Work Issues
Article Requests
Collaboration
General Discussions
Hardware
Algorithms / Math
Design and Architecture
Subtle Bugs
Suggestions
The Soapbox