Results 1 to 36 of 36

Thread: move cursor to beginning of line in textbox

  1. #1

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    move cursor to beginning of line in textbox

    Hi everyone,

    I am trying to move the cursor to the beginning of the current line in a textbox.
    This is a basic terminal program. Data comes in from the serial port and is displayed in the textbox.

    When the program receives a 13 (carriage return) from the serial port, it should bring the cursor to the beginning of the same line. All I have managed to do is bring the cursor to the beginning of the following line.

    Can anyone help me please?
    Any help is greatly appreciated!
    Code:
    '******************************************
    ' This procedure adds data to the Term control's Text property.
    ' It also filters control characters, such as BACKSPACE,
    ' carriage return, and line feeds, and writes data to
    ' an open log file.
    ' BACKSPACE characters delete the character to the left,
    ' either in the Text property, or the passed string.
    ' Line feed characters are appended to all carriage
    ' returns.  The size of the Term control's Text
    ' property is also monitored so that it never
    ' exceeds MAXTERMSIZE characters.
    '******************************************
    '
    Private Static Sub ShowData(Text1 As Control, Data As String)
        Dim TermSize As Long, i
        Dim lCurPos As Long, lLineLength
        TermSize = Len(Text1.Text)
    ' Point to the end of Term's data.
           Text1.SelStart = TermSize
           
      'Determine Cursor Position
    '         If Text1.SelLength = 0 Then
    '            lCurPos = Text1.SelStart
    '         Else
    '            lCurPos = Text1.SelStart + Text1.SelLength
    '         End If
    '     Determine the Line Length
    '     lLineLength = SendMessage(Text1.hwnd, EM_LINELENGTH, lCurPos, 0)
    
    ' Filter/handle BACKSPACE characters.
        Do
           i = InStr(Data, Chr$(8))
           If i Then
              If i = 1 Then
                Text1.SelStart = TermSize - 1
                Text1.SelLength = 1
                 Data = Mid$(Data, i + 1)
              Else
               Data = Left$(Data, i - 2) & Mid$(Data, i + 1)
              End If
           End If
        Loop While i
      ' Eliminate line feeds.
        Do
           i = InStr(Data, Chr$(10))
           If i Then
             Data = Left$(Data, i - 1) & Mid$(Data, i + 1)
           End If
        Loop While i
    '
    '******************************************
    ' Make sure all carriage returns have a line feed.
    'this is where I am stuck
    'I don't want to add a line Feed (Chr$(10))
    'I just want to position the curor at the beginning of the current line
    '******************************************
    '
        i = 1
        Do
           i = InStr(i, Data, Chr$(13))
           If i Then
       '       Data = Left$(Data, i) & Chr$(10) & Mid$(Data, i + 1)
              Data = Left$(Data, i) & Mid$(Data, i + 1)
              i = i + 1
           End If
        Loop While i
                 
        Text1.SelText = Data
        Text1.SelStart = Len(Text1.Text)
    Exit Sub
    
    Handler:
        MsgBox Error$
        Resume Next
    End Sub

  2. #2
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    You can send the EM_LINEFROMCHAR (to get the current line #) and EM_LINEINDEX (to get the character index of the start of the current line) messages to the TextBox to accomplish your goal.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Quote Originally Posted by jpbro View Post
    You can send the EM_LINEFROMCHAR (to get the current line #) and EM_LINEINDEX (to get the character index of the start of the current line) messages to the TextBox to accomplish your goal.
    are you sure those links are VB6?
    I am lost.

    Any examples?

  4. #4
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    They're messages that can be send to the underlying Win32 Edit window of the VB6 TextBox control. You will need to use the SendMessage API (there should be lots of examples around if you search for "SendMessage em_lineindex em_linefromchar VB6" in Google). Here's one resource I found that should clear things up a bit: http://vbnet.mvps.org/code/textapi/txapiselect.htm

  5. #5

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    This is kind of WAY over my head!

    I made an exe out of the code from the link, and it works.

    However, it only selects the line, it does not move the cursor to the start.

    I just want to move the cursor to the beginning of the line so the next data will overwrite the current data.

  6. #6
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    The code at the link was just to give you a nudge in the right direction, it's not the exact solution you are looking for.

    I had a look at the code at the link I provided, and it looks like the Command3_Click event gets you pretty close:

    Code:
    Private Sub Command3_Click()
    
       'Typically this would be called from
       'a menu item, for example 'Select To Beginning of Line'
        Dim cursorPos As Long
        Dim currLine As Long
        Dim chrsToCurrent As Long
        On Local Error Resume Next
       
       'get the cursor position in the textbox
        Call SendMessage(Text1.hwnd, _
                         EM_GETSEL, 0, cursorPos)
       
       'get the current line index
        currLine = SendMessage(Text1.hwnd, _
                               EM_LINEFROMCHAR, _
                               cursorPos, _
                               ByVal 0&) ' + 1
       
       'number of chrs up to the current line
        chrsToCurrent = SendMessage(Text1.hwnd, _
                                    EM_LINEINDEX, _
                                    currLine, ByVal 0&)
    
       'select from the first chr on the
       'cursor line up to the cursor
        Text1.SetFocus
        Call SendMessage(Text1.hwnd, _
                         EM_SETSEL, _
                         chrsToCurrent, _
                         ByVal cursorPos)
    
    End Sub
    Note the comment "Get the cursor position of the TextBox" - you can skip this part and use the TextBox.SelStart property instead.

    Next comment is "get the current line index" - this is a line of code you'll need because we need to figure out what line # the cursor is on. So you can do something like:

    Code:
       'get the current line index
        currLine = SendMessage(Text1.hwnd, _
                               EM_LINEFROMCHAR, _
                               TextBox1.SelStart, _
                               ByVal 0&)
    To get the line index of the SelStart of a control called TextBox1.

    The next comment is "number of chrs up to the current line" which is another way of saying get the starting character of the current line. So you can use this code verbatim to get the position you want to move the caret to:

    Code:
       'number of chrs up to the current line
        chrsToCurrent = SendMessage(Text1.hwnd, _
                                    EM_LINEINDEX, _
                                    currLine, ByVal 0&)
    Finally, you have to actually move the caret to the current line start index. You can do this as follows:

    Code:
    TextBox1.SelStart = chrsToCurrent
    I haven't actually tested the above, but it should work.

  7. #7

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    This is kind of WAY over my head!

    I made an exe out of the code from the link, and it works.

    However, it only selects the line, it does not move the cursor to the start.

    I just want to move the cursor to the beginning of the line so the next data will overwrite the current data.

  8. #8

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    thanks, I did figure out that it was command 3. I will have a look at the above and let you know how it goes.

    I appreciate your help!

  9. #9

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    I really appreciate your help, thanks again!

    Well I got it to work, but moving it over to my application is more difficult than I expected.

    When a carriage return comes in to the text box (Chr 13), the cursor should go to the start of the current line.

    When both a carriage return and a line feed comes in to the text box(Chr 13) & (Chr10), the cursor should go to the first position on the next line.

    This is what I have so far:
    Code:
    '*******************************************************
    ' This procedure adds data to the Term control's Text property.
    ' It also filters control characters, such as BACKSPACE,
    ' carriage return, and line feeds, and writes data to
    ' an open log file.
    ' BACKSPACE characters delete the character to the left,
    ' either in the Text property, or the passed string.
    ' Line feed characters are appended to all carriage
    ' returns.  The size of the Term control's Text
    ' property is also monitored so that it never
    ' exceeds MAXTERMSIZE characters.
    '*******************************************************
    Private Static Sub ShowData(Text1 As Control, Data As String)
        Dim TermSize As Long, i
        Dim lCurPos As Long, lLineLength
        Dim cursorPos As Long
        Dim currLine As Long
        Dim chrsToCurrent As Long
        On Local Error Resume Next
    '
        TermSize = Len(Text1.Text)
    ' Point to the end of Term's data.
           Text1.SelStart = TermSize
           
      'Determine Cursor Position
             If Text1.SelLength = 0 Then
                lCurPos = Text1.SelStart
             Else
                lCurPos = Text1.SelStart + Text1.SelLength
             End If
           'Determine the Line Length
        lLineLength = SendMessage(Text1.hwnd, EM_LINELENGTH, lCurPos, 0)
    
    ' Filter/handle BACKSPACE characters.
        Do
           i = InStr(Data, Chr$(8))
           If i Then
              If i = 1 Then
                Text1.SelStart = TermSize - 1
                Text1.SelLength = 1
                 Data = Mid$(Data, i + 1)
              Else
               Data = Left$(Data, i - 2) & Mid$(Data, i + 1)
              End If
           End If
        Loop While i
        '
            'Check for beep char, don't print beep char!
           i = InStr(Data, Chr$(7))    '7 = beep
           If i Then
       '    Beep
                Text1.SelStart = TermSize
                Text1.SelLength = 1
                 Data = Mid$(Data, i + 1)
           End If
        '
     	i = 1
            i = InStr(i, Data, Chr$(13))
           If i Then
            'get the current line index
        currLine = SendMessage(Text1.hwnd, _
                               EM_LINEFROMCHAR, _
                               Text1.SelStart, _
                               ByVal 0&)
    
    'number of chrs up to the current line
        chrsToCurrent = SendMessage(Text1.hwnd, _
                                    EM_LINEINDEX, _
                                    currLine, ByVal 0&)
           End If
    '
        Text1.SelText = Data 'put the data in the text box
    
    ' move the cursor to the current line start index.
    
    Text1.SelStart = chrsToCurrent
        Text1.SetFocus
    Exit Sub
    
    Handler:
        MsgBox Error$
        Resume Next
    End Sub

  10. #10
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    I don't see any handling of character code 10 in your code. You'll need to test for Chr$(10) and then you can bump down to the beginning of the next line using EM_LINEFROMCHAR with Text1.SelStart, then send EM_LINEINDEX with the result of EM_LINEFORCHAR message call + 1 (for the line after the current line), and finally set SelStart to the result of your EM_LINEINDEX call.

  11. #11
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: move cursor to beginning of line in textbox

    Seems like you need to update your header comment as well, since it seems like you might have a logic conflict with how you treat linefeeds since you say the code should add linefeeds when you receive a carriage return.
    Code:
    ' Line feed characters are appended to all carriage
    ' returns.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Hello Everyone,
    I realize this is an old post, however I decided to try this again.
    I have never been able to make it work as expected.

    What i am trying to achieve here is to move the cursor to the beginning
    of the current line when a cr (13 or 0x0D) is received. Then the subsequent
    text will overwrite the data on the current line, beginning at the start of the current line.

    Every other char (except 13) is passed to the textbox including the lf (line feed,10 or 0x0A).
    I hope someone can point out what I am doing wrong.
    Any help is greatly appreciated.

    This is what i have done:

    Code:
    Private Sub MSComm1_OnComm()
         
       Select Case MSComm1.CommEvent
    ' Handle each event or error by placing
    ' code below each case statement
         
          Case comEvReceive ' Received RThreshold # of chars.
          
                 Buffer = MSComm1.Input
        ShowData Text1, (StrConv(Buffer, vbUnicode))
    
          Case comEvSend ' There are SThreshold number of
                         ' characters in the transmit buffer.
            
             Do While MSComm1.OutBufferCount > 0
                DoEvents
             Loop
             
          Case comEvEOF  ' An EOF character was found in
                          ' the input stream
       End Select
       
    End Sub
    '----------------------------------------------------
    Private Static Sub ShowData(Text1 As Control, Data As String)
        Dim TermSize As Long, i
        Dim lCurPos As Long, lLineLength
        Dim cursorPos As Long
        Dim currLine As Long
        Dim chrsToCurrent As Long
        On Local Error Resume Next
    '----------------------------------------------------
        i = 1
            i = InStr(i, Data, Chr$(13))
    If i Then
    'we are here because we received a cr (0x0D)
    'the cursor needs to be at the beginning of the current line
    '
    'get the current line index
        currLine = SendMessage(Text1.hwnd, _
                               EM_LINEFROMCHAR, _
                               Text1.SelStart, _
                               ByVal 0&)
    
    'number of chrs up to the current line
        chrsToCurrent = SendMessage(Text1.hwnd, _
                                    EM_LINEINDEX, _
                                    currLine, ByVal 0&)
    'Determine the Line Length
        lLineLength = SendMessage(Text1.hwnd, EM_LINELENGTH, lCurPos, 0)
    
    Text1.SelStart = chrsToCurrent - lLineLength
    'Text1.SelStart = lCurPos - lLineLength
    End If
    
    'we are here because we received any other char other than Chr$13
    'put the text after the last char in the textbox
    '
    'count ALL the chars in the textbox
        TermSize = Len(Text1.Text)
        
    'Point to the end of Term's data.
           Text1.SelStart = TermSize
    
    'Determine Cursor Position
             If Text1.SelLength = 0 Then  'if beginning of Textbox
                lCurPos = Text1.SelStart
             Else
                lCurPos = Text1.SelStart + Text1.SelLength
             End If
             
    'Add the filtered data to the SelText property.
        Text1.SelText = Data
    Exit Sub
    
    Handler:
        MsgBox Error$
        Resume Next
    End Sub

  13. #13
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    If the textbox is in YOUR app, you're looking for a specific character within that textbox to move the cursor to (in this case, I assume a vbCr) and you've been told about .selstart...I don't see why you still haven't figured it out.

    Simply do an instrrev(textbox.text,vbCr) on the box, and use textbox.seltext with the result.

    Code:
    textbox.seltext instrrev(textbox.text,vbCr)+1
    Obviously replace textbox with the name of the textbox, so in your case I assume

    Code:
    Text1.seltext instrrev(Text1.text,vbCr)+1
    This would move the cursor to the last line (not the current line your cursor is on...you can probably work out how to do that with .selstart to get the current cursor position) though wouldn't overwrite it...I'm nudging you towards the answer though, hopefully

  14. #14
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    Ummm, sure, we can do anything with API calls, but what's wrong with:

    Code:
    
    Option Explicit
    
    Private Sub Form_Click()
        Me.Text1.SelStart = 0
        Me.Text1.SelLength = 0
    End Sub
    
    
    Just a Form1, with a Text1 on it. Clicking the form resets Text1's carat.

    ---------------

    Ahhh, beginning of Line in Multiline textbox. Yeah, I think SmUX2k is on the right track.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  15. #15
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    Or here, this moves it to the beginning of the current line.

    Code:
    
    Option Explicit
    
    Private Sub Form_Click()
        Me.Text1.SelLength = 0
        Me.Text1.SelStart = InStrRev(Me.Text1.Text, vbLf, Me.Text1.SelStart)
    End Sub
    
    
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  16. #16

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Thanks for the response guys. I tried the code in #15 and it does nothing different in my code.
    The cursor does not go to the beginning of the line.

    However it seems to work in a new project with just a text box and command button.
    I don't know what i am doing wrong in my code.

    here is my code:
    Code:
    Private Sub MSComm1_OnComm()
         
       Select Case MSComm1.CommEvent
    ' Handle each event or error by placing
    ' code below each case statement
         
          Case comEvReceive ' Received RThreshold # of chars.
          
                 Buffer = MSComm1.Input
        ShowData Text1, (StrConv(Buffer, vbUnicode))
    
          Case comEvSend ' There are SThreshold number of
                         ' characters in the transmit buffer.
            
             Do While MSComm1.OutBufferCount > 0
                DoEvents
             Loop
             
          Case comEvEOF  ' An EOF character was found in
                          ' the input stream
       End Select
       
    End Sub
    '----------------------------------------------------
    Private Static Sub ShowData(Text1 As Control, Data As String)
        Dim TermSize As Long, i
        Dim lCurPos As Long, lLineLength
        Dim cursorPos As Long
        Dim currLine As Long
        Dim chrsToCurrent As Long
        On Local Error Resume Next
    '----------------------------------------------------
        i = 1
            i = InStr(i, Data, Chr$(13))
    If i Then
    'we are here because we received a cr (0x0D)
    'the cursor needs to be at the beginning of the current line
    '
       Me.Text1.SelLength = 0
        Me.Text1.SelStart = InStrRev(Me.Text1.Text, vbLf, Me.Text1.SelStart)
    Debug.Print "Text1.SelStart = " & Text1.SelStart
    	Exit Sub
    End If
    
    'we are here because we received any other char other than Chr$13
    '
    'count ALL the chars in the textbox
        TermSize = Len(Text1.Text)
        
    'Point to the end of Term's data.
           Text1.SelStart = TermSize
    
    'Determine Cursor Position
             If Text1.SelLength = 0 Then  'if beginning of Textbox
                lCurPos = Text1.SelStart
             Else
                lCurPos = Text1.SelStart + Text1.SelLength
             End If
             
    'Add the filtered data to the SelText property.
        Text1.SelText = Data
        Text1.SetFocus
    End Sub
    Last edited by ckeays; Mar 19th, 2024 at 01:16 PM.

  17. #17
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    It might need a vbCr rather than a vbLF, but from what you say above it is receiving a full vbCrLf so that shouldn't matter.

    Is the cursor moving at all?

    You might want to debug.print Me.Text1.Selstart both before and after the line that is setting the Selstart to see if it is actually changing anything, and PERSONALLY I would be setting the app to break on that line anyway to use the immediate window to test if instrrev is returning anything but 0 when I use it...if you do that you can play around to see what works best

    ANOTHER option you have if you can't seem to figure this out...how about building a helper function that takes in the data and processes it, reformatting it as needed to ensure that the data in the textbox HAS vbCrLf at the end of each line and the rest of the data is uniform and as expected...it could be the source of the data that is causing issues here

  18. #18

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Quote Originally Posted by SmUX2k View Post
    It might need a vbCr rather than a vbLF
    With just the basic app (textbox and command button),
    what that does is move the cursor to the above line, in the middle somewhere.
    So vbLF is needed to make it work.

    Quote Originally Posted by SmUX2k View Post
    Is the cursor moving at all?
    Yes but not to the beginning of the line. The cursor goes to the end of the text in the text box.
    This is from debug.print while running. This should only print if 13 is received.
    Code:
    Text1.SelStart = 226
    Text1.SelStart = 251
    Text1.SelStart = 251
    Text1.SelStart = 265
    Text1.SelStart = 265
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 284
    Text1.SelStart = 328
    Text1.SelStart = 328
    Text1.SelStart = 328
    Text1.SelStart = 328
    Quote Originally Posted by SmUX2k View Post
    it could be the source of the data that is causing issues here
    I think you are right. The data is being formatted:
    Code:
        i = 1
            i = InStr(i, Data, Chr$(13))
    If i Then
    I have updated the source code in my last post to reflect the changes.

  19. #19
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    If it's going to the end of the text box that probably means that it's positioning itself either in or before the vbCrLf...try adding a +1 or +2 (+1 for vbCr or vbLf, +2 if it's always vbCrLf) on the selstart value (you'll notice *I* did, but Elroy didn't, include this :-P ...I've done a lot of code adjusting for line breaks in text )

  20. #20

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Quote Originally Posted by SmUX2k View Post
    If it's going to the end of the text box that probably means that it's positioning itself either in or before the vbCrLf...try adding a +1 or +2 (+1 for vbCr or vbLf, +2 if it's always vbCrLf) on the selstart value (you'll notice *I* did, but Elroy didn't, include this :-P ...I've done a lot of code adjusting for line breaks in text )
    I don't think the cursor is going to the end of the textbox, it's going to the end of the existing text in the textbox, then new chars are added there.

    I did try your suggestion (+1, or +2) nothing has changed.

  21. #21
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    Are you trying to go to the beginning of a "wrapped text" textbox, or are you trying to go to the beginning of line "when your lines are terminated with vbLF"?

    If you're trying to go to the beginning of a line of wrapped text, that's an entirely different problem. And it's not easily solved. It'd take a lot of gyrations with .TextWidth and figuring out which line you were actually on ... basically re-calculating all of the wrapping logic.

    I've never had a need for that in VB6, and doubt I ever will. That's full-blown word-processor stuff.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  22. #22
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    Quote Originally Posted by ckeays View Post
    I don't think the cursor is going to the end of the textbox, it's going to the end of the existing text in the textbox, then new chars are added there.

    I did try your suggestion (+1, or +2) nothing has changed.
    Bear in mind that if you add text to the textbox it is going to be added at the current selection point...so if you want a specific line that you select to be the focal point you'll need to grab the .selstart before adding anything to the textbox...I suspect this isn't the problem as you seem to want to replace that line with the text so you weren't adding to the textbox at this point...possibly worth mentioning though.

    I wonder if the .selstart and instrrev() is finding the vbCr (chr(13)) at the very end of the line and assuming that's the one you want? Try changing the second selstart (that is part of the instrrev() ) by adding "-1" at the end of it

    Code:
    Me.Text1.SelStart = InStrRev(Me.Text1.Text, vbLf, Me.Text1.SelStart-1)+1
    Also, perhaps it would be handy to post an example of the text that is incoming...possibly not, as it may be re-formatted if you post it as text, so I would write it to a file (literally write the contents of the textbox to a text file) and upload it here so we can have a look. Feel free to edit out anything you don't want public. Also, if you do this, explain again in the SIMPLEST way possible (imagine I'm a manager and you're a coder working under me :-P ) exactly what you want to do and what you expect to happen, and also what is actually happening. Keep each line short, one line per requirement/expectation.

  23. #23

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Many Thanks for responding! I am sure what I am doing wrong is something very simple.
    Quote Originally Posted by SmUX2k View Post
    I wonder if the .selstart and instrrev() is finding the vbCr (chr(13)) at the very end of the line and assuming that's the one you want? Try changing the second selstart (that is part of the instrrev() ) by adding "-1" at the end of it
    Code:
    Me.Text1.SelStart = InStrRev(Me.Text1.Text, vbLf, Me.Text1.SelStart-1)+1
    I tried that, same thing, data goes to the end of the text in the same line.

    Quote Originally Posted by SmUX2k View Post
    Also, perhaps it would be handy to post an example of the text that is incoming.
    Here is a log of what is being sent:
    teraterm.txt

    I created a very short video of how the text should look when the file is sent.
    For the demonstration, I just sent the file between two virtual serial ports using
    https://www.hhdsoftware.com/virtual-serial-port-tools
    Its free to use for 14 days.

    The forum won't allow the video to be uploaded so I uploaded it here:
    https://drive.google.com/file/d/1lVc...ew?usp=sharing

    What is supposed to happen is the incoming text is a 16 bit address that is sent like this:
    00 space 00 cr then 00 space 01 cr then 00 space 02 cr...

    What is happening with my code in the text box is:
    Code:
    00 0004 0008 000C 0010 00
    the cr is after every address 00 00 CR 04 00 CR, etc so the program is totally missing the 13 (CR) char.

    I hope someone has an idea on how I can figure this out. I do know how to debug with VB6
    so if you have any ideas, I am all ears!

    When attempting to Debug.Print the char that was received from MSCOM, it shows every char except
    CR or LF, they appear as " ".

    Any help is greatly appreciated.
    Last edited by ckeays; Mar 19th, 2024 at 04:07 PM.

  24. #24
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    This works for TextBoxes with lines that wrap:

    Code:
    Option Explicit
    
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageW" (ByVal p_Hwnd As Long, ByVal p_Msg As Long, ByVal p_WParam As Long, ByVal p_LParam As Long) As Long
    Private Declare Function SetFocusApi Lib "user32.dll" (ByVal p_Hwnd As Long) As Long
    
    Private Const WM_KEYDOWN As Long = &H100
    Private Const WM_KEYUP As Long = &H101
    
    Private Const EM_LINEINDEX As Long = &HBB
    Private Const EM_LINEFROMCHAR As Long = &HC9
    
    Private Sub MoveToFirstCharOfCurrentLine(po_TextBox As VB.TextBox)
       Dim l_CurrentLine As Long
       Dim l_FirstCharOfLine As Long
    
       On Local Error Resume Next
    
       'get the current line index
       l_CurrentLine = SendMessage(po_TextBox.hWnd, _
                              EM_LINEFROMCHAR, _
                              po_TextBox.SelStart, _
                              0&)
    
       'number of chrs up to the current line
       l_FirstCharOfLine = SendMessage(po_TextBox.hWnd, _
                                   EM_LINEINDEX, _
                                   l_CurrentLine, _
                                   0&)
    
       SetFocusApi po_TextBox.hWnd
       If l_FirstCharOfLine = 0 Then
          po_TextBox.SelStart = 0
       
       Else
          ' Hack to work around caret rendering bug - it draws at the end of the previous line on word-wrapped lines
          ' even though caret is actually at the start of the current line
          
          po_TextBox.SelStart = l_FirstCharOfLine - 1
          SendMessage po_TextBox.hWnd, WM_KEYDOWN, vbKeyRight, 0&
          SendMessage po_TextBox.hWnd, WM_KEYUP, vbKeyRight, 0&
       
       End If
    End Sub
    
    Private Sub Form_Click()
       MoveToFirstCharOfCurrentLine Me.Text1
    End Sub

  25. #25
    PowerPoster
    Join Date
    Aug 2010
    Location
    Canada
    Posts
    2,412

    Re: move cursor to beginning of line in textbox

    Just watched the video - if you are constantly replacing the text and there's always 4 hex characters separated by a space, why not use a label instead and just change the caption? Do you need to be able to edit the text at some point?

  26. #26
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    Ok, that's very weird text:

    Name:  Image1.png
Views: 60
Size:  16.1 KB

    Lines are terminated ONLY by a vbCR. In Windows environments, they're typically terminated by a vbCr & vbLf (aka, vbCrLf). In Unix/Linux environments, lines are typically terminated by only vbLf.

    But it's VERY unusual to have a text file with only vbCR line terminations. But that's you're problem.

    Do this:

    Code:
    sInputText = Replace(sInputText, vbCr, vbCrLf)
    And then shove that into your textbox. Then it'll work.

    ----------------

    Or, I suppose you could replace the vbLF with a vbCR in my post #15, and that would fix it as well.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  27. #27
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    .
    More typical text:

    Name:  Image2.png
Views: 61
Size:  16.8 KB
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  28. #28

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Guys correct me if I am wrong here but won't adding a LF to the CR will just make the cursor go to the next line?
    The reason only the cr is there is so that the address being shown will be overwritten each time. For long files, the textbox would be full really fast this way.

    Programs like Teraterm support this, (they call it VT100 emulation).
    If the file was sent with Teraterm to another instance of Teraterm the output would be just like the video I posted.
    If the file is sent from Teraterm to my VB6 program the cr is skipped as I mentioned in #23 above.

  29. #29

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Quote Originally Posted by jpbro View Post
    Just watched the video - if you are constantly replacing the text and there's always 4 hex characters separated by a space, why not use a label instead and just change the caption? Do you need to be able to edit the text at some point?
    There are two characters then a space then two more characters followed by a CR (13).
    I did try this with a label once but without success because I could not find a way to distinguish an address from other numbers in the incoming text.

  30. #30
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,853

    Re: move cursor to beginning of line in textbox

    Gemini:

    No, VT100 emulation isn't limited to just CR (Carriage Return) for terminating lines. In fact, by default, CR alone isn't used in VT100 emulation.

    Here's the breakdown:

    • VT100 newline behavior: VT100 terminals typically used a combination of CR and LF (Line Feed) to represent a newline character. CR moves the cursor to the beginning of the current line, and LF moves it down one line.
    • Emulator configuration: VT100 emulators often provide options to configure how they interpret newline characters. You can choose between CR+LF (default VT100 behavior), LF alone (common on Unix-based systems), or CR alone (less common).
    Your text is just weird, and needs to be massaged to work correctly.
    Last edited by Elroy; Mar 19th, 2024 at 04:34 PM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  31. #31
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    I suspect you have a misunderstanding of how text boxes work. If you had "AS DF(CR)" in the textbox, there would be 6 characters. If you then added "QW ER(CR)" it would have 12 characters. Adding text to a textbox doesn't "overwrite" the text if you don't go to a new line, it will continue growing and growing in size.

    Hopefully now you'll see why I asked you to explain what you expected to see as if we were idiots...it's helped us work out many root causes of your problem(s) and given us things we can point out that will help you improve your code :-)

    A textbox is multiline unless you set multiline to false, which I assume you do based on the description. If you only want the current address shown, the best thing to do would be to have (as I mentioned) a helper function which parses the data as it comes in. Once it sees a CR, it takes all new data from the buffer (except the CR) and pastes it into the textbox (replaces contents, does NOT ADD TO CONTENTS!) then clears the buffer including the CR. That way you'll see it take in "AS DF", it'll see the CR and paste it into textbox, then it'll see "QW ER" and paste that into textbox (replacing "AS DF") when it sees the CR, finally it'll see "ZX CV" and paste that into the textbox (again, replacing "QW ER") when it sees the next CR. This helper function should filter out any non-visible characters, so only the ones you expect should be added to buffer (A-Z, a-z and 0-9 plus space...and any other characters you expect should be allowed).

    You could instead go with Elroy's solution but if you only need to display the most recent value you probably don't need to go so extreme with processing...mine is probably tidier :-)

  32. #32

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    thanks guys.
    I am just not experienced enough with VB to do this by myself.

    The helper function seems like the way to go.
    I assume that the entire contents of the textbox will be stored in a buffer then edited and replaced on every single character?

    Any links I can read up on to figure this out?

  33. #33
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    Check this out as an example of what I was on about...this is a REALLY simple example, with a button and two text boxes...click the button and every 300ms a new char will come into the buffer...when it sees CHR(13) it moves data from buffer to output...simple yet effective :-)
    Attached Files Attached Files

  34. #34
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    Things to note, in case you don't know:

    The "Public" variables at the top are public to the entire project...this means they can be called from any part of the project, they aren't local to one place...this would be how you set a buffer up, preferably.

    Adding two strings together is done with &. "Text1 & Text2" will take the contents of those two textboxes and put them together in a new variable, which you would set with "newvar = Text1 & Text2" (or you can set Text1 OR Text2 to hold the data, there's not many limits). It is exactly the same with strings, and you can have "buff = buff & chr(incomingvalue)" which will add the value to the buffer and make the buffer easily readable (it doesn't have to be an on-screen textbox, though you might prefer that TBH). There are more efficient ways to deal with string data, but you don't need that level of complexity as it's only a few bytes.

    There are plenty of other ways to manipulate strings, though none of them are particularly useful here...but you should learn them all, ready for when you need them. Things like strconv(), asc(), chr(), mid(), left(), right() for example...and I am sure there will be others.

  35. #35
    Hyperactive Member
    Join Date
    Apr 2021
    Posts
    481

    Re: move cursor to beginning of line in textbox

    Oh, and you can probably literally copy over the helper function from my demo and make a few small changes (setting output and buffer, for example) then can tie it into your incoming data and report each character to it as it comes in and let it do its stuff...and it REALLY isn't a complicated function :-)

  36. #36

    Thread Starter
    Junior Member
    Join Date
    May 2019
    Posts
    17

    Re: move cursor to beginning of line in textbox

    Thank you to everyone for the time you spent trying to help me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width