Handling backspace in a RichTextBox - again!

Hello,

I'm revisiting a problem I've never solved satisfactorily.  I have a 
multi-line RichTextBox that receives text input from a serial port (not the 
keyboard); that input frequently contains backspace characters.  To handle 
the backspace characters I'm currently calculating the offset of the 
character to be backspaced over from the beginning of the entire text box, 
selecting that character, then replacing it with no character.  The "for" 
loop in the code below calculates the length of everything in the text box.  
While this scheme has worked correctly, it really slows the system down as 
the contents of the text box increases.  It seems that ideally I should be 
able to deal only with the last line in the text box instead of having to 
treat everything in the text box as one big long string, but I haven't 
figured out a way to do this.  Another brutal alternative to recalculating 
the entire length of the text box each time a backspace character is 
encountered would be to manually keep a running count of the total number of 
characters as they are added and subtracted, and this would doubtless speed 
things up significantly.  However, it seems that there still should be a 
better way.

Thanks,
Ray

***** I execute the following code each time a backspace character is 
encountered:

int displayLineCount = display.Lines.Length;
if (displayLineCount > 0)
{
   string lastLine = display.Lines[displayLineCount - 1];
   int lastLineLength = lastLine.Length;
   if (lastLineLength > 0)
   {
      // Get count of all characters from beginning of display up to the 
current line.
      // For purposes of calculating character offset of the last display 
character from
      // the beginning of the display, the length of each line is considered 
to be 1 plus
      // the number of characters on that line.
      int length = 0;
      for (int lineNo = 0; lineNo < displayLineCount - 1; ++lineNo)
         length += display.Lines[lineNo].Length + 1;
      display.Select(length + lastLineLength - 1, 1);
      display.SelectedText = "";
      display.SelectionStart = length + lastLineLength - 1;
   }
}

0
Utf
7/1/2010 7:47:11 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

3 Replies
2043 Views

Similar Articles

[PageSpeed] 56

Ray Mitchell wrote:
> Hello,
> 
> I'm revisiting a problem I've never solved satisfactorily.  I have a 
> multi-line RichTextBox that receives text input from a serial port (not the 
> keyboard); that input frequently contains backspace characters.  To handle 
> the backspace characters I'm currently calculating the offset of the 
> character to be backspaced over from the beginning of the entire text box, 
> selecting that character, then replacing it with no character.  The "for" 
> loop in the code below calculates the length of everything in the text box.  
> While this scheme has worked correctly, it really slows the system down as 
> the contents of the text box increases.

Even the code you posted could be improved.  You should not need to 
recalculate the character position of interest from the contents of the 
control, since your own code is the code adding text to it (and so can 
easily keep track of that information).  And you should also only 
retrieve the Lines property value once; the array being returned has to 
be recreated each time you get the property value, and as the amount of 
text increases, that's a lot of data to be copied.

But I think all of that is actually not relevant.  It's not clear to me 
why you're calculating the text position the way you are, even ignoring 
its implicit assumption that the newline is only one character (have you 
checked to make sure that if "\r\n" is used as the newline, the text box 
control converts that to a single character?).  After all, in the end 
you are just trying to delete the last character of the text, right? 
Why not just use the TextLength property to determine the correct 
character offset?

So, assuming the backspace character should always just delete the last 
character in the control, it seems to me that the following should work 
just as well, and be much more efficient:

   int ichDelete = display.TextLength - 1;

   display.Select(ichDelete - 1, 1);
   display.SelectedText = "";
   display.SelectionStart = ichDelete;

(And actually, I haven't tested...it's possible that last line isn't 
required, since the selection has to wind up _somewhere_ after the 
delete and it's likely that the control will just put the text cursor in 
the location where you've just deleted the text).

> It seems that ideally I should be 
> able to deal only with the last line in the text box instead of having to 
> treat everything in the text box as one big long string, but I haven't 
> figured out a way to do this.  Another brutal alternative to recalculating 
> the entire length of the text box each time a backspace character is 
> encountered would be to manually keep a running count of the total number of 
> characters as they are added and subtracted, and this would doubtless speed 
> things up significantly.  However, it seems that there still should be a 
> better way.

See above.

Beyond that, you may recall that a couple of years ago, I pointed you to 
a simple custom control implementation I'd written as a demo but which 
could be modified to suit your needs.  In particular, by writing a 
custom control, you then have direct access to the internal data 
structures, and can provide whatever public API to the control class 
that best fits your usage scenarios.  I think that you can do much 
better with the RichTextBox class than you currently are, but it may 
well be that eventually you find it's just too limited.

If so, you may want to revisit this discussion:
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d4c6ff994e2286d7/ae29018b8c504219

Pete
0
Peter
7/1/2010 9:40:56 PM
"Peter Duniho" wrote:

> Ray Mitchell wrote:
> > Hello,
> > 
> > I'm revisiting a problem I've never solved satisfactorily.  I have a 
> > multi-line RichTextBox that receives text input from a serial port (not the 
> > keyboard); that input frequently contains backspace characters.  To handle 
> > the backspace characters I'm currently calculating the offset of the 
> > character to be backspaced over from the beginning of the entire text box, 
> > selecting that character, then replacing it with no character.  The "for" 
> > loop in the code below calculates the length of everything in the text box.  
> > While this scheme has worked correctly, it really slows the system down as 
> > the contents of the text box increases.
> 
> Even the code you posted could be improved.  You should not need to 
> recalculate the character position of interest from the contents of the 
> control, since your own code is the code adding text to it (and so can 
> easily keep track of that information).  And you should also only 
> retrieve the Lines property value once; the array being returned has to 
> be recreated each time you get the property value, and as the amount of 
> text increases, that's a lot of data to be copied.
> 
> But I think all of that is actually not relevant.  It's not clear to me 
> why you're calculating the text position the way you are, even ignoring 
> its implicit assumption that the newline is only one character (have you 
> checked to make sure that if "\r\n" is used as the newline, the text box 
> control converts that to a single character?).  After all, in the end 
> you are just trying to delete the last character of the text, right? 
> Why not just use the TextLength property to determine the correct 
> character offset?
> 
> So, assuming the backspace character should always just delete the last 
> character in the control, it seems to me that the following should work 
> just as well, and be much more efficient:
> 
>    int ichDelete = display.TextLength - 1;
> 
>    display.Select(ichDelete - 1, 1);
>    display.SelectedText = "";
>    display.SelectionStart = ichDelete;
> 

As usual Pete, very helpful answer.  Thanks very much.  The code above 
worked great, except that "ichDelete - 1" should be "ichDelete". 

> (And actually, I haven't tested...it's possible that last line isn't 
> required, since the selection has to wind up _somewhere_ after the 
> delete and it's likely that the control will just put the text cursor in 
> the location where you've just deleted the text).
> 
> > It seems that ideally I should be 
> > able to deal only with the last line in the text box instead of having to 
> > treat everything in the text box as one big long string, but I haven't 
> > figured out a way to do this.  Another brutal alternative to recalculating 
> > the entire length of the text box each time a backspace character is 
> > encountered would be to manually keep a running count of the total number of 
> > characters as they are added and subtracted, and this would doubtless speed 
> > things up significantly.  However, it seems that there still should be a 
> > better way.
> 
> See above.
> 
> Beyond that, you may recall that a couple of years ago, I pointed you to 
> a simple custom control implementation I'd written as a demo but which 
> could be modified to suit your needs.  In particular, by writing a 
> custom control, you then have direct access to the internal data 
> structures, and can provide whatever public API to the control class 
> that best fits your usage scenarios.  I think that you can do much 
> better with the RichTextBox class than you currently are, but it may 
> well be that eventually you find it's just too limited.
> 
> If so, you may want to revisit this discussion:
> http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d4c6ff994e2286d7/ae29018b8c504219
> 
> Pete
> .
> 
0
Utf
7/2/2010 1:33:31 AM
Ray Mitchell wrote:
> [...]
>>    int ichDelete = display.TextLength - 1;
>>
>>    display.Select(ichDelete - 1, 1);
>>    display.SelectedText = "";
>>    display.SelectionStart = ichDelete;
>>
> 
> As usual Pete, very helpful answer.  Thanks very much.  The code above 
> worked great, except that "ichDelete - 1" should be "ichDelete". 

Quite right.  Sorry about that.  Managed to apply the "one character 
from the end" logic twice.  :)
0
Peter
7/2/2010 1:40:27 AM
Reply:

Similar Artilces:

Having issues handling combo-box
I have a combo-box. I want to allow folks to enter by typing OR use the mouse to click on the dropdown. If they type I want it to auto-complete - that is no problem as the drop list style handles this. Where my problem arises is that when they pick the one they want I then need to know so I can do some added processing. I could handle the kill focus for when they type but that causes confusion when they use the mouse. What I want to be able to do is recognize when they hit <Enter> and act in a manner similar to that used when they use the mouse to pick an entry. The other possibili...

How is SMTP handled in a NLB setup ?
We have two FrontEnd Exchange 2003 servers setup in a Network Load Balanced "cluster" - our BackEnd server uses the NLB cluster as smart host for outgoing SMTP.. Can we be sure that all outgoing mail is sent as coming from the common NLB cluster-IP-number or could it be possible that under certain conditions mail is sent as coming from the IP-number of the indivudal server handling the transaction ? Our worry is whether we need to register both the NLB cluster-IP and the individual server-IP's in external DNS - to enable sender verification in all circumstances ? Thank...

How Exchange2003 handle auto-reply loop?
Hi there, For Exchange2003 with Outlook2003, user1 and user2 both set "out of office" auto reply rule, then I send email to both user1 & user2, user1 & user2 will start generate auto reply loop. Wondering if Exchange2003 has some mechanism to detect such auto reply loop & stop it? Also how about the case if user1 is internal user, while user2 is external user? Can Exchange2003 detect such auto reply loop & stop it? Many thanks! Well, first of all, just turning on the Out of Office rule will not create loops any more, because Out of Office Assistant will o...

? Handling WM_SIZE/WM_SIZING But Not From Restore
Hi, I need to handle WM_SIZE and WM_SIZING but only for when the size of the window is actually changing, not for when it is being restored from a minimized state (yes, I know it's technically changing in that case.) I've got a resizing dialog app which has a list control in in. I've set up the dialog to move and resize the list control as well as set the column widths whenever the dialog's size is altered (in OnSize). However, this is a waste of time when the dialog is just being restored from a minimized state, specifically if the list control has lots of items in it (you...

Changing which server handles outgoing mail
Hi... I have three Exchange servers in my site (Let's call them E1, E2, E3) E1 is Exchange 5.5 and was the first server in the site. E2 is an Exchange 2000 server to which all the mailboxes from E1 were moved a while back. This is basically the one we run from. It appears that this is the server that sends all my outgoing mail. E3 is another Exchange 2000 server (much faster hardware) that I just recently brought up and my plan is to eventually move all of my users from E2 to it. Just for testing purposes, I created a test mailbox on E2, then moved the mailbox to E3. I was able to ...

How to handle special "sentinal" characters encoded on magstripes
I purchased a card printer and encoder planning on starting a loyalty program. I encoded the customer account number, but when I swipe the card to look-up the customer, my reader includes the start and end characters in the lookup field (accessed through F7 on the POS screen). I think those characters are required to be there, but is there a way to handle them on the look-up? This is a multi-part message in MIME format. ------=_NextPart_000_08B0_01C6F6F2.F5F99190 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable Brain, Turn off the sta...

Money 2003 401k Handling
From pat posts I've read on this newsgroup, it would seem that Money's handling of 401k accounts is somewhat dorked up. Here's my problem: I've always tracked my 401k simplistically, using "Update This Account" out of the "401k Manager" Screen. Recently I created a new dupe 401k and tried using the Update Retirement Account wizard with all my old statements, so I could track company matching and dividends. This worked great until I got to a point where I transferred money out of one fund into another. I added the new fund, checked it's checkbox, and ...

HANDLE hFile
Hi all, I am having a problem.. I used HANDLE hFile = CreateFile(_T(fileName), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); to create a log file for my application and It works on debug mode. When i run my application on Release mode it says cannot create file. any help would be great.. Thanks, -- -thiru Call GetLastError() and see what the error is. -- Cheers Check Abdoul ------------------ "Thiru" <Thiru@discussions.microsoft.com> wrote in message news:8E6F4631-42C7-4353-944F-35691DDAB6AF@microsoft.co...

Does CRM 4.0 handle Partner management?
We are a software shop and we are currently using CRM 3.0, with the expectation to upgrade to 4.0 in the very near future. One of our newest directives is to manage our partners, and their accounts using CRM and we are wondering if 4.0 will be better at managing this? I realize this is kind of vague, but its something that the sales staff is asking of me. Microsoft released a CRM accelerator for Partner Management in October. take a look at it here: http://crmaccelerators.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29990 Hello Rodney, You could be interested in our CRM @Comme...

Multiple Recipients Handling
With an email message that has multiple recipients in the header, can I configure Exchange to break-up that header up so that only 1 recipient is in the message before delivery? For example, if I send an email message to person1@somewhere.com and person2@nowwhere.org, can I have Exchange break that up into 2 separate e-mail messages before sending? Thanks. Hi, ShootMePlease wrote: > With an email message that has multiple recipients in the header, can > I configure Exchange to break-up that header up so that only 1 > recipient is in the message before delivery? > > Fo...

Close button and RichTextbox
How do I get rid of (or disable) the little Close button at the upper right hand corner on a child form? I have only figured out how to hide the Maximum and Minimum buttons, but not the Close button. Any suggestion? Also, how to determine the number of lines entered in a RichTextbox? Where can I retrieve that piece of information? Thanks!! "C.L." <anonymous@discussions.microsoft.com> wrote in message news:027f01c3ad99$28a9bd00$a401280a@phx.gbl... > How do I get rid of (or disable) the little Close button > at the upper right hand corner on a child form? I have &g...

when deleting text hit backspace more than once delete paragraph?
I am working in publisher 2007, every time i make a mistake and go to correct the error, when pressing backspace key more than once, it automatically selects the entire paragraph and if i hit it one more time it erases the entrie paragraph? Why does it do this? is this a know problem with the beta2? I believe you should be able to press the backspace (delete) key as many times as you want to delete text, i dont want to use the mouse when typing to correct mistakes. This doesn't happen with my beta, could be a repair would help. I had an issue with the Document Imaging so I repaire...

Handling contacts in accounts
Can anyone suggest the best way to deal with a contact who leaves a company and reappears in another company. Should the contact just be reassigned, or should they be left (deactivated?) in the existing company, and a new contact created. I am interested in tracking history both with the old account, and with the contact themselves. Technojeff, you can use the relationships to do this. Reassign your contact to the new company, add a relationship between the contact and old company. HTH, Frederic - Travi@ta www.microsoft-dynamics-crm.eu technojeff schreef: > Can anyone suggest the...

Problem handling keyboard events in ActiveX on IE8
Hi All, I have a ActiveX control which was working fine till now. I was using IE7 as the ActiveX container. I handle the keyboard events using PreTranslateMessage. But since i switched to IE8 the keyboard events are not being passed to my activex control. If i press backspace in a edit control on my ActiveX, the browser gets re-directed to the previous page. Also i'm not able to debug the ActiveX control since i switched to IE8. Why am i not able to debug my application? Any help is highly appreciated. Thanks, Bharath I made some changes to the Internet explorer registry an...

Handle GPIO in Freescale MX25PDK BSP
Has anyone done any simple subproject to Freescale WINCE 6 MX25PDK BSP that toggle, set or clear an IO / GPIO ? If anyone could provide me with such a sampleproject I would be more than happy. I seem to get compiler errors as soon as I try myself... However I do I get this kind of errors: BUILD: [01:0000000092:ERRORE] S4_IO_TEST.obj : error LNK2019: unresolved external symbol DDKGpioSetConfig referenced in function WinMain BUILD: [01:0000000093:ERRORE] obj\ARMV4I\debug\S4_IO_TEST.exe : fatal error LNK1120: 1 unresolved externals Any tiå is greatly appreciated. ...

Pie chart handles in the pivot table don't function
Hi All: I have a pie chart which activates off a pivot table. I want to expand the pie chart size so that I can see it better, and I can't get the "pull" handles to work? Please advise. Really need this one answered right waay, as I am missing a deadline! Thanks, Hazel Hi, I don't believe you can resize the plotarea for a pie chart, or in fact any chart, when it is linked to a pivot table. You will need to make your own chart based on the cells. But don't you the mouse to select the cells otherwise it will create an automatic link to the pivot table and ...

The 'sizing handles' on the axis titles don't work!!
I'm working with a column chart in Excel - I'm trying to resize the title box of the y-axis, but I can't. When I double-click, I see the thick line and the dark boxes of the sizing handles. However, when I try to use these, I get no double-headed arrow and can't resize the box. I can move it around, but that's all. I can't resize the chart title and x-axis titles either. Weirdly, I CAN resize the legend box. Anyone know how I can fix this? Nicole, Unfortunately the only way that you can resize the title box is to change the font size. You still get the borders...

CEdit ampersand character handling
I need to modify a CEdit control to handle the ampersand character like any other character (no special handling). Something equivalent to SS_NOPREFIX on static controls (or DT_NOPREFIX in a DrawText call). It seems that when the edit control has focus, the displayed text shows the ampersand as is. When the control loses focus, the & is interpreted as an accelerator prefix and shows as an underline of the next character, so changing single ampersand to double ampersand will show ok when the control does not have focus but is changed to double ampersand when the edit control gets foc...

Handling Catch Weight Items (Like Cheese)
Anyone know if there is a 3rd party module that provides Catch-Weight functionality? Basically, this is the ability to charge a client for the total weight of all the cases but account for the # of cases in inventory. Each case will have a slightly different weight. Thanks, Bradley Trinity Computer Services has a product that does just that. See them at http://www.trinitypartner.com/. Note that it is partner not partners. The "s" will take you to another site. Trinity was the company that developed the advanced distribution modules. They have some neat add on modules for ...

ERR:The target cannot handle this type of document. ??
I get this err when coping, (bckup), a NEW or old file -> to a NEW or used disk in A:/, (floppy). I feel like I'm "skatin' on thin ice", without bckups! Boswell abe@isp.com Hello- It is best to _not_ try to read/write any Office files directly to or from floppies or (most) other removable media. Save As to your hard drive, then use Windows Explorer to move/copy to the target destination. Regards |:>) "B. abe@isp.com" wrote: > I get this err when coping, (bckup), a NEW or old file -> to a NEW or used > disk in A:/, (floppy). > I feel like ...

Rebuilding MFC and .inl file handling
Hi folks. We also have been bit by the VS.Net 2003 bug where CFile::GetFileName(), CFile::GetPathName(), and CFile::GetStatus() throw an exception when reading a file from a CD-ROM drive (due to an exception thrown in one of the CTime constructors within CFile::GetStatus). Since we have to recompile the MFC source already anyway (we're using Unicows), we figured we'd try editing the atltime.inl file and recompiling MFC. In debug mode, we reasoned, atltime.inl finds its way into a library, so linking to a version of MFC with that code changed would solve our problem, right? Well, wr...

How to handle context menu in tree view
Hi, for some reason I cannot handle context menu in handler for WM_CONTEXTMENU message. Actually, code executes when I double right click the mouse. This problem only appears in CListView and view derived from it. So I decided to handle NM_RCLICK notification but NMHDR structure is of no help as it doesn't show coordinates where the click occured. But I solved that problem. My question is why I can't handle WM_CONTEXTMENU message with just one right click? natko >for some reason I cannot handle context menu in handler for WM_CONTEXTMENU >message. Actually, code executes whe...

Outlook message handling when replying to all.
Rescently whenever I click "Reply To All" to reply to all addresses in the original message, when I send the message instead of it being marked with the curved arrow in my inbox indicating it was replied to, it is removed from my inbox completely. A copy is saved in sent items but that is simply because I have sent the message but it does not indicate that is was replied to (other than the obvious indication that it is in the sent items). I assume there must be an option for this as it has just started doing this and is kind of annoying! Any help is appreciated!! Thanks! ...

GDI handles
In taskmanager I see the amount of used GDI and user objects per process. How can I achieve this using a powershell script on Windows XP using PowerShell 1.0? The result should be a list with all process names, PIDs and amount of used GDI objects. I played with the following: PS H:\> (Get-WmiObject -Class Win32_OperatingSystem -ComputerName ..).InvokeMethod("GetGuiResources",0) Method invocation failed because [System.Management.ManagementObject#root\cimv2\Win32_OperatingSystem] doesn't contain a method named 'InvokeMethod'. At line:1 char:74 + (G...

Handle on cell selector disappeared..
Hi, Fired up excel today just to see a very strange problem.. no handles on selections at all. When I select the cells, its just a simple selection.. no little cross at the bottom right. Can't drag, copy .. do anything. Any suggestions on how to bring the handles back on? Farhan. Hi Farhan, It looks like the option "Allow cell drag and drop" is deactivated. From the Tools menu, click on Options, then check "Allow cell drag and drop" in the Edit tab. Does it work now? Best regards Stefan H�gglund Microsoft "Farhan Ata Arain" <j_kirk65Z@yahoo.c...