The window being printed must be visible and contain focus

1.3k Views Asked by At

I'm trying to print a form when a button is a button is clicked on another form. However, I am getting an error message during run-time causing my program to crash.

On the printreceipt form there is a PrintForm Object

I want to print the "PrintReceipt" form without having to place a button on the form.

Code in print button

  PrintReceipt.PrintForm1.Print()

Error Message

The window being printed must be visible and contain focus

Thanks for any help you can provide

2

There are 2 best solutions below

0
On

Add these two lines on the top of the form:

Imports System.Drawing.Printing
Imports Microsoft.VisualBasic.PowerPacks.Printing

It will work perfectly.

1
On
    Me.PrintForm1.PrintAction = Printing.PrintAction.PrintToPreview
    'PrintForm1.PrinterSettings.DefaultPageSettings.Landscape = True
    PrintForm1.PrinterSettings.DefaultPageSettings.Margins = New System.Drawing.Printing.Margins(0, 0, 0, 0)
    For Each size As PaperSize In PrintForm1.PrinterSettings.PaperSizes
        If size.Kind = PaperKind.A4 Then
            PrintForm1.PrinterSettings.DefaultPageSettings.PaperSize = size
            Exit For
        End If
    Next
    PrintForm1.Print(Me, PrintForm.PrintOption.ClientAreaOnly)
    Me.Refresh()