views:

182

answers:

3

How can I do some code when the user changes what line the caret is on?

so something like:

sub textbox1_lineindexchanged (byval ....) Handles Textbox1.Lineindexchanged
  'do code based on the current line
end sub

sorry, I am using a richtextbox, just I always used it so I just call it a textbox in my thoguhts.

A: 

There is no way to do this with a vanilla WinForms TextBox instance. It doesn't expose any information about the caret. The only way to do this would be to sub-class TextBox, override WndProc and specifically handle messages about caret movement (if such messages exist).

What behavior are you trying to achieve here? There may be another way to achieve this.

JaredPar
it does through textbox.SelectionStart, and then you can just check if the selectionlength is 0. And you can get the currentline by `TextBox1.GetLineFromCharIndex(TextBox1.GetFirstCharIndexOfCurrentLine)`
Jonathan
A: 

I assume you are using Windows Forms so my answer is based on that. If you are using ASP.NET then you'll need to do it with JavaScript and I have no idea how/if that's possible.

In Windows Forms, you can create an event handler for the KeyUp and MouseUp events but there is no SelectionChanged event. If you switch to using a RichTextBox instead, you do have access to a SelectionChanged event.

In the event you would use the SelectionStart property of the textbox and pass that to the GetLineFromCharIndex method which will give you the line number. Hope this helps.

Josh Einstein
but I don't what to go through the code if the caret has just moved left/right.
Jonathan
Then what you want to do is not possible.
Josh Einstein
Well actaully the code I want to run when the line changes is a function on a usercontrol which has to store the line of text anyway, so I'll just check if the line the caret is on is the same as the one stored in the user variable. If they are the same then the caret hasn't moved line (or if there are 2 identical lines I don't need to run the code anyway) if they're not then it's moved line or the lines been changed and I need to run the code for both of those circumstances. So thanks!!!!
Jonathan
A: 

I doubt there's something more elegant than checking SelectionStart property from KeyPress, Click, and TextChanged handlers.

GSerg