How to Print Multiline Text Box Contents to Printer or Picture

ID Number: Q84555

1.00

WINDOWS

Summary:

When trying to print the contents of a multiline text box in Visual

Basic to the printer or to another control, you must use Windows API

calls to determine where each line ends and the next begins. The

SendMessage API along with the EM_GETLINECOUNT and EM_GETLINE

constants can provide you the number of lines in the text box as well

as the text from that particular text box.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

Multiline text boxes do not embed carriage returns and linefeeds into

the Text property of the text box. Therefore, if you try to print the

Text property to a printer, picture control, or form, you end up with

one long line of text.

To print the text of the picture box as it appears in the multiline

text box, do the following:

1. Run Visual Basic, or from the File menu, choose New Project (ALT,

F, N) if Visual Basic is already running. Form1 is created by

default.

2. Put a text box (Text1) on Form1.

3. Change the Multiline property of Text1 to True.

4. Add a picture control to the form, making it about the same size as

the text box.

5. Add the following declare statements to your GLOBAL.BAS file or

your general Declarations section:

' GetFocus returns the handle of the window with the focus.

Declare Function GetFocus% Lib "user" ()

' SendMessage sends a message to the specified window

' Note: the following declare should be on one line

Declare Function SendMessage% Lib "user"

(ByVal hwnd As Integer, ByVal wMsg As Integer,

ByVal wparam As Integer, ByVal lparam As Any)

6. Add the following code to the Form_Click procedure:

Sub Form_Click ()

WM_USER = &H400

EM_GETLINECOUNT = WM_USER + 10

EM_GETLINE = WM_USER + 20

' Set the focus to the text box and then get it's handle

Text1.SetFocus

texthwnd% = getfocus()

' Get the number of lines in the text box

numlines% = sendmessage(texthwnd%, EM_GETLINECOUNT, 0, 0&)

' Clear the picture control

Picture1.Cls

' Loop through all lines of text

For i% = 0 To numlines% - 1

x$ = Space$(100)

' Get next line of text

numchars% = sendmessage(texthwnd%, EM_GETLINE, i%, x$)

' Print x$ to the picture control

Picture1.Print x$

' Send the string to the printer at this point

' Printer.Print x$

Next

End Sub

6. Press F5 to run the program.

7. Type a few lines of text into the text box.

8. Click on the form. The text appears in the picture box as it

does in the text box.

You can also use this procedure to print to the printer, print to a

form, or send text via DDE to other applications. The only thing you

will need change is be the Print statement in the Form_Click procedure.

Additional reference words: 1.00