RichTextBoxExtended - The Code Project - C# C...

来源:百度文库 编辑:神马文学网 时间:2024/04/30 13:33:13
 
3,675,800 members and growing!   8,998 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
RichTextBoxExtended
ByRichard Parsons.
A RichTextBox with a richtext toolbar.
C#
Windows, .NET (.NET 1.1)
Win32, VS (VS.NET2003), GDI+
Dev
Posted: 10 Feb 2005
Updated: 21 Jun 2006
Views: 67,869
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
55 votes for this article.
Popularity: 8.1. Rating: 4.65 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 source and demo - 176 Kb

Introduction
Hello again, my friends. Today‘s control is a very simple yet useful control. It is a custom control that contains both a RichTextBox and a Toolbar. Now you might ask: "Why is that so important and useful?" It‘s because I have taken the liberty to do some coding for you. The toolbar not only looks pretty but it‘s functional too. It contains some of the everyday, plain, and simple things you want your users to be able to do when they input text.
Background
[Cheesy flashback music and graphics.] It all started when I was trying to remember how to insert a rich text "stamp" into a RichTextBox. Along the road to remembering, I thought to myself "Self, wouldn‘t it be easier not to have to remember this stuff every 6 months?" My answer was a big yes. It would be easier if I just built a control to use every time I needed users to input text. Then thinking of all the wonderful and helpful people on The Code Project, I decided to distribute my control so that everyone can learn how to do this stuff and also so they will have a pre-built control for use whenever they want.
Using the control
There are two ways you can use this control. You can either add the RichTextBoxExtended.cs file to your project and use the control by setting it up in code, or you can add the control to your toolbar and drag it on to your Form. One other thing, if you add the .cs file to your project, you will also have to add an ImageList to your project that contains all the images for the Toolbar. I prefer (and suggest) the latter method because I get to see the control on the form and I don‘t have to create the ImageList on every form I want to use this control on.
There are several properties that will help you use this control, and they are listed below:
AcceptsTab AutoWordSelection ReadOnly ShowBold ShowCenterJustify ShowColors ShowCopy ShowCut ShowFont ShowFontSize ShowItalic ShowLeftJustify ShowOpen ShowPaste ShowRedo ShowRightJustify ShowSave ShowStamp ShowStrikeout ShowUnderline ShowUndo StampColor StampAction Toolbar - only use at runtime, changes that are made at design time will not persist. RichTextBox - only use at runtime, changes that are made at design time will not persist.
Out of all of these, most of them are simply turning features on and off. The only really special ones are StampColor, StampAction, Toolbar, and RichTextBox.
StampColor is what it sounds like. It is the color the text will be in when a stamp is added to the RichTextBox. StampAction can be one of three values: EditedBy, DateTime, or Custom. EditBy is a string that reads "Edited by " + CurrentPrincipal.Identity.Name + " (theUserName) on " + DateTime.Now.ToLongDateString(). DateTime: DateTime.Now.ToLongDateString(). Custom: For Custom, you must handle the stamp event of this control.
Collapse
private void richTextBoxExtended1_Stamp(object sender, System.EventArgs e) { //holds our stamp text StringBuilder stamp = new StringBuilder(""); if(richTextBoxExtended1.RichTextBox.Text.Length > 0) stamp.Append("\r\n\r\n"); //add two lines for space stamp.Append("Custom stamp goes here!\r\n"); //unselect everything basicly richTextBoxExtended1.RichTextBox.SelectionLength = 0; richTextBoxExtended1.RichTextBox.SelectionStart = richTextBoxExtended1.RichTextBox.Text.Length; //start new selection at the end of the text richTextBoxExtended1.RichTextBox.SelectionColor = richTextBoxExtended1.StampColor; //make the selection blue richTextBoxExtended1.RichTextBox.SelectionFont = new Font(richTextBoxExtended1.RichTextBox.SelectionFont, FontStyle.Bold); //set the selection font and style richTextBoxExtended1.RichTextBox.AppendText(stamp.ToString()); //add the stamp to the richtextbox richTextBoxExtended1.RichTextBox.Focus(); //set focus back on the richtextbox } Points of Interest
The biggest point of interest after all these months now is the amount of feedback, interest, and work one little control can bring to your life. I haven‘t been able to maintain this code like I wanted but thanks to all that have helped and made suggestions along the way. Along with this updated article comes news of RichTextBoxExtended for Framework 2.0. So if you want all these features in VS 2005 then keep watching. Anyone wanting to help, just email me.
OK, so what did I learn from this control and this experience? I learned about Exclusive-OR. This is a really handy operation that saved me 100 or so lines of code in this control. In the code below, the OR is the "^". The best way I can explain it is, it takes two values like 00000001 and 00000010 and compares them. In the example below, it checks the style and if the style = 00000001, it will change it to 00000000, however if it is 00000000, then it will change it to 00000001. That isn‘t the best explanation of this operation, so below the code are some links for you.
rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style ^ FontStyle.Bold);C# Programmer‘s Reference - ^ Operator.Masks and flags using bit fields in .NET by Edward Smoljanovic.
History
1.0 - Initial release - 1/31/2004. 1.1 - 4/18/2005. Font Selector added. Font Size Selector added. Fixed error that caused the control to crash when two or more font types were selected. Cleaned up the code.
1.2 - 12/12/2005 Fixed multiple font selection bug. You can now add font styles (e.g. Bold and Color) when selecting two different fonts at the same time. Added a selection change event named SelChanged. Added cut, copy and paste buttons. The control now uses the ToolBarButton.Tag property instead of the ToolBarButton.ToolTip property for button presses. Now you can have your tooltips be whatever you like. Added DetectUrls property. You can have HTTP links in your RichTextBox and click them to open the system default browser. Added a ReadOnly property. Added AcceptsTabs property. Added AutoWordSelection property. Added keyboard handler for Ctrl+B, Ctrl+I, Ctrl+S, Ctrl+U, Ctrl+-. The download now comes with all the images. I also included a print image. Cleaned up the code.
About Richard Parsons
Richard is a contract developer that currently lives in Arkansas. He has spent most of his career working in healthcare related companies. On his first job he was programming asp using VBScript and his boss walked in and told the whole group to get in their cars and drive to Barnes and Nobles. Once there he let everyone buy a few books about .NET and then he dropped the bomb, he said we would no longer write asp code. Starting Monday we were to be .NET developers.
Five years later Richard is a competent and self motivated .NET developer that can tackle most any problem. He has recently started his own businessBellaDev which is proving to be a fun and challenging opportunity. Clickhere to view Richard Parsons‘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 25 of 122 (Total: 122) (Refresh) First PrevNext
Subject  Author  Date

 toolbar repaint problem  merkuriev_sergey  6:39 28 Dec ‘06
  If it control put to the tab control then toolbar stops repaint and impose drawing one to another.
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Intellectual Property Rights  Flying Jett  19:02 7 Dec ‘06
  Richard, hello.
Your control is very useful for my application. How
about intellectual property right on this control ? In which case I could use it without problems in my app ?
Thank you in advance for answering.
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Intellectual Property Rights  Richard Parsons  8:55 13 Dec ‘06
  You may use the control in any free or commercial app with out charge.
Richard
http://www.BellaDev.net
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Intellectual Property Rights  Flying Jett  9:08 17 Dec ‘06
  Thank you =)
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Subscript and Superscript.  chris175  9:16 16 Nov ‘06
  An easy way to use these features would be to derive your RichTextBox control fromhttp://www.codeproject.com/cs/miscctrl/htmlrichtextbox.asp?forumid=231253&mpp=50&select=1760849&df=100&msg=1760849[^]. This control provides other functionaity as well.
Chris
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Subscript and Superscript.  Richard Parsons  17:28 16 Nov ‘06
  Thanks for the heads up about that article but it really wouldn‘t help me out to much because my control actually uses rtf properties to format the text while his control parses a small subset of html to format the text.
Richard
http://www.BellaDev.net
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 WOW  chris175  7:57 8 Nov ‘06
  WOW this is great!!!!!!!!!!!!!
The project is built with .Net 7.1 and converting it to 8.0 was no work at all. Work perfectly...
Chris
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 very good  amin keshani  3:43 17 Oct ‘06
  good work
thank
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 good work  vik20  5:23 28 Sep ‘06
  Liked the work. Thanks for posting
Vikram
http://www.vikramlakhotia.com
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Why won‘t this work?  gafferuk  1:30 27 Aug ‘06
  I have 2 RichTextBoxExtended on a form and i have following code added to a button:
richTextBoxExtended1.RichTextBox.Rtf = richTextBoxExtended1.RichTextBox.Rtf;
Any ideas?
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Why won‘t this work?  Richard Parsons  9:47 29 Aug ‘06
  Well since I don‘t know what you are trying to do I‘ll guess at it
If you are using the above code absolutely nothing will happen because you are referencing richTextBoxExtended1 on both sides of the equation. If you are trying to set richTextBoxExtended2 equal to richTextBoxExtended1 then you need to fix that line to read as follows:
richTextBoxExtended2.RichTextBox.Rtf = richTextBoxExtended1.RichTextBox.Rtf;
If you are trying to do something else please let me know and I‘ll try and help,
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Control keys not working for Cut, Copy, & Paste  cbumstead  18:39 9 Aug ‘06
  I‘m using RichTextBoxExtended in .NET 2.0 and CTRL-X, CTRL-C, and CTRL-V do not seem to work. Any suggestions?
Also, the tab key does not work as it is getting intercepted by the method:
private void rtb1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if((int)e.KeyChar == 9)
e.Handled = true; // Stops Ctrl+I from inserting a tab (char HT) into the richtextbox
}
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Control keys not working for Cut, Copy, & Paste  Richard Parsons  11:37 10 Aug ‘06
  Hey cbumstead, I‘m not sure what is going on. I downloaded the project here at work today and compiled it. Then I added it to another project and all the functionality that you are missing is working for me? All I can suggest is making sure you have the latest version because CP didn‘t have the newest zip file for awhile and someone brought that to my attention so it just got updated here recently.
-Richard
[Reply |Email |View Thread |Get Link] Score: 2.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Control keys not working for Cut, Copy, & Paste  cbumstead  21:19 16 Aug ‘06
  Richard,
My appologies. I had inserted a menu bar and selected the standard items in the application I am building that uses your RichTextBoxExtended. The "standard items" included cut, copy and paste and were handling the control keys before the rich text box could.
Thanks
- Chad
[Reply |Email |View Thread |Get Link] Score: 5.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Fix for DataBinding DBNull.Value  Paul Brower  10:30 7 Aug ‘06
  Rich text boxes throw up if you have a databinding on the ‘Rtf‘ property, and the value is null or DBNull.value.
I have been using your control (I think it‘s great), but I would recommend implementing the following to solve the DBNull.Value databinding issue:
1. Create a new event in the contstructor:
public EventHandler RtfBindingChanged ;
2. Create a new property
[Bindable(true)]
public object RtfBinding
{
get
{
return this.RichTextBox.Rtf ;
}
set
{
if (value == DBNull.Value || value == null)
{
this.RichTextBox.Rtf = "" ;
}
else
{
this.RichTextBox.Rtf = value.ToString() ;
}
if (RtfBindingChanged != null)
{
RtfBindingChanged(this,EventArgs.Empty) ;
}
}
}
Now, whenever you are binding to this control, you should use the following format:
[RTFExtendedControl].DataBindings.Add("RtfBinding",[datasource],[columnname]) ;
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Fix for DataBinding DBNull.Value  Richard Parsons  10:00 8 Aug ‘06
  Thanks for the info Paul, I‘ll try and get those changes in the code soon. You may want to also check outPersisting Rich Text[^]. It‘s an article done by another CPian to update my control to persist data and it has a fancy UIType Editor for the RTF property.
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 How can i add the RichTextBoxExtended to my toolbox ?  joshuaduder  21:21 2 Aug ‘06
  Hi Richard can you please tell me how to add the RichTextBoxExtended to my toolbox ?
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: How can i add the RichTextBoxExtended to my toolbox ?  Richard Parsons  9:55 3 Aug ‘06
  1. Download the source and demo project from above
2. Open the solution and compile as Release not Debug
3. Open a new or existing project in VS
4. Right click 1n the general toolbox
5. Select Add/Remove Items
6. Click Browse
7. Navigate to the location of the RichTextBoxExtended.dll
8. Click Open
9. Click Ok
It should now show up in your toolbar under the General section.
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Dotfuscated  Graham Dean  16:31 10 Jul ‘06
  Whoops - it‘s that bl**dy Pensioner again Richard!
Have now nearly got my program doing what it should, so I thought it about time to obscure all my efforts using Dotfuscator (Community Edition by Premptive Solutions) - especially to hide the ‘back door‘!. After a long learning curve (and not yet complete), everything works except loading the form for RTBE! I have a lot more testing to do, but wondered if you had any bright ideas? Could it be to do with the ‘control in a control‘?
Pensioner Graham Dean
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Dotfuscated  Graham Dean  11:04 11 Jul ‘06
  Got there in the end - select option to preserve Namespace and it all works!
Cheers
Pensioner Graham Dean
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Dotfuscated  Richard Parsons  9:15 12 Jul ‘06
  Cool beans. Saves me from having to find the time
I‘m so busy these days that I have even put off the framework 2.0 version of this control for now.
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 License [modified]  Piotr Karczmarz  5:27 31 May ‘06
  How about the license ? Can I use your control in commercial app ?
--
Piotr Karczmarz
www.karczmarz.com
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: License [modified]  Richard Parsons  9:35 1 Jun ‘06
  You sure can. The only thing I ask is that I get a screenshot of the application form that contains the control, and that is optional. I just want to see how and where people use this thing
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 print .rtf with c++.net  hfariza  5:53 17 May ‘06
  How do I print a *.rtf file using c++.net? So far it prints along with the formatting such as \par, \tab, etc. Or how can I print the content of a RichTextBox?
Please advise.
fariza
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: print .rtf with c++.net  Richard Parsons  9:57 18 May ‘06
  Well I‘m not a C++ guy and currently don‘t have time to even play around with a c# solutions but here are a few links that I think will get you going in the right direction:
http://www.codeproject.com/managedcpp/managedcppwordpad.asp[^]
http://www.codeproject.com/csharp/qedprinter.asp[^]
Sorry I couldn‘t be more help,
-Richard
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

Last Visit: 10:53 Wednesday 3rd January, 2007 First PrevNext
General comment   News / Info   Question   Answer   Joke / Game   Admin message
Updated: 21 Jun 2006 Article content copyright Richard Parsons, 2005
everything else Copyright ©CodeProject, 1999-2006.
Web12 |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