You can save a lot of code by using the TextChange event. Every time it fires, either trim the newlines or revert to a previous version of the field that you’ve saved. If the latter, and there are no newlines, save the contents, SelStart and SelLength so you can restore them later if needed.
TextChange will cover you no matter how the text is updated, be it typing, pasting, or drag-and-dropping.
I think Xojo prevents recursion of that event internally, but your advice is still sound. Otherwise, every keystroke would cause the user to lose their place in the field.
In this case, they yield the same result, but ChrB will return a single byte whereas Chr will return a unicode character that may be up to four bytes internally.
ChrB should only be used when you are dealing with “raw bytes” held in a string (ie/ read from a binary stream, or socket). Any time you have"textual data" you should use Chr. Using ChrB on data that already has a proper encoding will set the encoding to NIL and you can cause yourself to have weird effects as mentioned in:
I am saving to a custom xml document format with UTF-8 encoding. All text is generated by the user in listboxes, textareas, and textfields would be internally stored as UTF-8 as well.
if instr(me.text,chr(10)+instr(me.text,chr(13)>0 then Me.Text = ReplaceLineEndings(me.text, " ")
In terms of optimization, using separate If conditions would be faster. The way that’s written, it’s forced to look for a CR even if it already found a LF.
if me.Text.InStr( Chr( 10 ) ) <> 0 or me.Text.InStr( Chr( 13 ) ) <> 0 then ...
In practice, I don’t know if you’d be able to measure the difference.
I’ve updated the code to also account for SelStart and optimization. The user is prevented from typing any endoflines in a textfield or textarea. Textareas can still display multiple lines of text such as a large paragraph but not include any endoflines. If any text is pasted or dragged into these controls any endoflines are replaced with spaces.
TextChange
If Instr(Me.Text, EndOfLine) > 0 then
Dim S as String
Dim I as Integer
S = Me.Text
I = Me.SelStart
S = ReplaceLineEndings(S, " ")
Me.Text = S
Me.SelStart = I
End If
KeyDown
If Asc(Key) = 3 or Asc(Key) = 10 or Asc(Key) = 13 then
Return True
End If