Extending the TextBox Control
Easy wasn't it? What did you say? - Too easy? Well, let's do something a little more complicated then? Let us write a function that extracts a single line of text from the textbox. The message we need to use is called EM_GETLINE and it takes the line index in the wParam argument and a buffer string to save the text line in as the lParam argument.
Although this sounds faily easy, the problem is that the message requires that the max length of the string to return be saved in the first word of the buffer. A word is a 16-bit value. How can we save such a value in a VB unicode string? The answer is we can't. So what's the solution then? Well, we have to use a byte array and then convert it to a string afterward.
Public Const EM_GETLINE = &HC4 Public Function GetLine(txtBox As TextBox, _ LineIndex As Long) As String Dim bBuffer( ) As Byte 'the byte array Dim lngLength As Long 'the max length of the line Dim sRetVal As String 'the text to return 'check to see if the LineIndex value is valid If LineIndex >= LineCount(txtBox) 'call the LineCount function shown above Exit Function 'bale out End If 'get the length of the line lngLength = LineLen(txtBox, GetCharFromLine(txtBox, LineIndex)) 'check that there is any text on the line If lngLength < 1 Then Exit Function End If 'ReDim the byte array ReDim bBuffer(lngLength) 'Save the length in the first word of the array bBuffer(0) = lngLength And 255 bBuffer(1) = lngLength 256 'Send the message SendMessage txtBox.hWnd, EM_GETLINE, LineIndex, bBuffer(0) 'Finally convert the byte array into a string and return it sRetVal = Left$(StrConv(bBuffer, vbUnicode), lngLength) GetLine = sRetVal End Function
As you can see there is a lot you can do to extend the functionality in the standard VB controls. And these are just a few of the messages you can use on a textbox. Some of the others are:
EM_CANUNDO - Determines if you can undo the last editing or not.
EM_UNDO - Undo the last editing.
EM_GETMODIFY - Determines if the text in the textbox has been modified. Great to check if you make an editor and want to know if the text have to be saved or not.
EM_SETMODIFY - Manually set the modify flag to true or false. This flag is automatically set to true when the text changes.
I have written a class called cTextBoxEx, with an accompanied demo application, which use all of the mentioned messages and also add a function to delete a single line from the textbox. Furthermore it adds a couple of shortcuts as well. These are CTRL+A to select all and CTRL+Y to cut the current line and put it on the clipboard.
Page 3 of 3
This article was originally published on November 20, 2002