Solved

Print PictureBox1

Posted on 2011-02-22
17
714 Views
Last Modified: 2012-05-11
Hello all,

I want to create a VB button that will print my PictureBox1 withh everything in it.

How can i do this?

Thanks
0
Comment
Question by:Wilder1626
  • 11
  • 3
  • 3
17 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34957532
You say "with everything in it"...do you have things being displayed in the Paint() event or possibly some other controls inside the PictureBox?

...or does it only have something in the Image() Property?
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34959478
What i did it to put a picture box in my form and then, put labels, textbox, another picture inside it.
0
 
LVL 5

Expert Comment

by:andr_gin
ID: 34959935
A PictureBox only displays an image. Do you mean a GroupBox?
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34960073
So i should change it to a GroupBox instead of a picturebox?

In VB6 i was using a picture box.
0
 
LVL 5

Expert Comment

by:andr_gin
ID: 34960391
These two controls have completely different functionality:

A PictureBox only displays an image, for example your company logo. It has an Image property and some settings for display (stretch, zoom, center and so on).

A GroupBox is a Container that can hold multiple controls like TextBoxes, ListBoxes, PictureBoxes and so on.
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34960478
Oh ok, i will start by changing that.

After, i just need to know how i can print that GroupBox1.

Thanks for the information.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34960666
*Just to clarify, when you placed controls "in" the PictureBox you were really placing them ON or OVER the PictureBox.  It is technically possible for a PictureBox to "contain" controls but that can only be done at run-time via code.  If you move the PictureBox you'll see that the controls "within" it do NOT move along with it.

In addition to a GroupBox, you could also use a Panel.  To print it, you can tell the container to draw itself with Draw
ToBitmap(), then use that in a PrintDocument via DrawImage():


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)
        Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)

        ' ...Print bmp in PrintDocument with DrawImage()...
    End Sub

Open in new window

0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34960692
Ok,

I will try this at home tonight and i will let you know the result.

Thanks for the help.

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 11

Author Comment

by:Wilder1626
ID: 34968580
Ok, i have change the picturebox for a panel1.

I'm having a problem now with the preview bellow. The page is blank.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            PrintPreviewDialog1.Document = PrintDocument1
            PrintPreviewDialog1.ShowDialog()
        Catch exp As Exception
            MsgBox("An error occurred while trying to load the " & _
                "document for Print Preview. Make sure you currently have " & _
                "access to a printer. A printer must be connected and " & _
                "accessible for Print Preview to work.", MsgBoxStyle.OkOnly, _
                 Me.Panel1.ClientRectangle)
        End Try
    End Sub

Open in new window

0
 
LVL 5

Accepted Solution

by:
andr_gin earned 250 total points
ID: 34968716
1.)
Did you set the content of the PrintDocument anywhere.

Here is some test code I wrote 2 years ago to access a label printer via Windows printer driver. It prints 100 lines of code on some pages:

 Private Sub Button20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button20.Click
        For i As Integer = 0 To 100 - 1 'Generate 100 lines of Text
            TextToPrint(i) = i & " 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" & vbCrLf
        Next

       'Calculation of the Page Size (Required for a label printer, for a laser A4 printer it is a nice-to-have)
        Dim DPIFactor As Double = 100 / 25.4 'Convert from 0.01" to mm

        Dim PageSettings As New PageSettings
        PageSettings.PrinterResolution.X = 300
        PageSettings.PrinterResolution.Y = 300
        PageSettings.PaperSize = New PaperSize("Standard", 108 * DPIFactor, 25 * DPIFactor) 'My label was 108mmx25mm, you should use your PageSize instead

        Dim Dialog As New PrintDialog() 'The Printer Dialog
        Dialog.Document = New PrintDocument() 'Create the Document for the printerdialog
        Dialog.Document.DefaultPageSettings = PageSettings 'Set the pagesettings (if default settings are OK for you, you dont need that)
        Dim Result As DialogResult = Dialog.ShowDialog 'User pressed OK (otherwise abort)
        If Result <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If

        Dim Document As New PrintDocument() 'Now create the real document (didnt remember any more why I didnt used the original document
        Document.OriginAtMargins = False
        Document.DocumentName = "Testdatei von agi"
        Document.PrinterSettings = Dialog.PrinterSettings 'Set the printer settings

        AddHandler Document.PrintPage, AddressOf PrintPage 'Add Handler for page printing
        Document.Print() 'Start printing
    End Sub

    Private Pos As Integer = 0

   'Is called every time a page can be spooled ot the printer (5 pages, 5 times called)
    Private Sub PrintPage(ByVal sender As PrintDocument, ByVal e As PrintPageEventArgs)
        Dim LineCount As Integer = e.PageBounds.Height \ (20 + 5) 'Calculate how many lines of text fit on the page (in your case you have to calculate the size of the image

        For i As Integer = 0 To LineCount - 1 'Print all lines that fit on the page
            If Pos = 100 Then 'No more date => done
                Exit For
            End If

            Dim YPos As Integer = e.PageBounds.Top + (20 + 5) * i 'Draw one line below the other
            e.Graphics.DrawString(TextToPrint(Pos), New Font("Arial", 10), Brushes.Black, 0, YPos) 'Draw the text to the graphic
            Pos += 1
        Next

        If Pos < 100 Then 'If there is more text to print, set HasMorePages to true => function gets called again, if you dont set it (or to false) you are done printing
            e.HasMorePages = True
        End If
    End Sub

2.) Just a warning for the DrawToBitmap function. This does not work for every control For example a RichTextBox does not work correctly. This is because showing the RichTextBox uses some sort of hardware acceleration.
If your Form is not overlapped by other controls you can simply copy the content from the screen:
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/1454d078-c312-4741-88df-aa7eb306fe51/

Guess this works for your whole panel too.
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 250 total points
ID: 34969822
Yeah...you need to handle the PrintPage() event and use its supplied "e.Graphics".  The Bitmap should be at class (Form) level so it can be accessed in that event as well when you use DrawImage().
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34971243
Ok thanks, i will try andr_gin code.

I will let you know.
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34985585
Hello all,

Back again.

I have worked on it since 2 days but i still have an issue.

When i print my Panel1, it print diffrent from what we see.

ex:I have some label, visible = false, but when print, it show etc.

See picture.

What can i do to print what i see on the active form with panel1?




Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Static page As Integer = 1
        Dim startPosition As Integer = (page - 1) * PrintDocument1.DefaultPageSettings.Bounds.Height
        Static maxPages As Integer = 0

        If page = 1 Then
            For Each ctrl As Control In Me.Panel1.Controls
                If TypeOf ctrl Is TextBox Or TypeOf ctrl Is Label Or TypeOf ctrl Is PictureBox Then
                    ctrl.Tag = Int((ctrl.Top + ctrl.Height) / PrintDocument1.DefaultPageSettings.Bounds.Height) + 1
                    If CInt(ctrl.Tag) > maxPages Then maxPages = CInt(ctrl.Tag)
                End If
            Next
        End If

        For Each ctrl As Control In Me.Panel1.Controls
            If CInt(ctrl.Tag) = page Then
                If TypeOf ctrl Is TextBox Or TypeOf ctrl Is Label Then
                    Dim sf As New System.Drawing.StringFormat
                    If TypeOf ctrl Is TextBox Then
                        If DirectCast(ctrl, TextBox).TextAlign = HorizontalAlignment.Right Then
                            sf.Alignment = StringAlignment.Far
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                    ElseIf TypeOf ctrl Is Label Then
                        If DirectCast(ctrl, Label).TextAlign = ContentAlignment.TopLeft Then
                            sf.Alignment = StringAlignment.Near
                        ElseIf DirectCast(ctrl, Label).TextAlign = ContentAlignment.TopRight Then
                            sf.Alignment = StringAlignment.Far
                        End If
                    End If
                    sf.FormatFlags = StringFormatFlags.NoClip
                    e.Graphics.DrawString(ctrl.Text, ctrl.Font, New SolidBrush(ctrl.ForeColor), New RectangleF(ctrl.Left, ctrl.Top - startPosition, ctrl.Width + 50, ctrl.Height), sf)
                ElseIf TypeOf ctrl Is PictureBox Then
                    e.Graphics.DrawImage(DirectCast(ctrl, PictureBox).Image, New PointF(ctrl.Left, ctrl.Top - startPosition))
                End If
            End If
        Next

        page += 1
        If page > maxPages Then
            e.HasMorePages = False
            page = 1
            maxPages = 0
        Else
            e.HasMorePages = True
        End If
    End Sub

Open in new window




Print.jpg
Frame.jpg
form-activate.jpg
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34987234
This is the form4 and also the print preview diffrences
diffrences.jpg
0
 
LVL 11

Author Comment

by:Wilder1626
ID: 34989061
Ok,did some more test.

Now, it is good but i have only half of my panel.
Since i have a scroll baron my panel, i only see the image where i didn't scroll.

How do I print the scrollable panel?




Private Sub btnButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnButton3.Click
        CapturePanel()
        PrintDocument1.Print()
    End Sub
    Private Sub CapturePanel()
        Dim mygraphics As Graphics = Me.CreateGraphics()
        Dim s As Size = Me.Panel1.Size
        memoryImage = New Bitmap(s.Width, s.Height, mygraphics)
        Dim memoryGraphics As Graphics = Graphics.FromImage(memoryImage)
        Dim dc1 As IntPtr = mygraphics.GetHdc
        Dim dc2 As IntPtr = memoryGraphics.GetHdc
        With Panel1.ClientRectangle
            BitBlt(dc2, 0, 0, .Width, .Height, dc1, Panel1.Location.X, Panel1.Location.Y, 13369376)
        End With

        mygraphics.ReleaseHdc(dc1)
        memoryGraphics.ReleaseHdc(dc2)

    End Sub

Open in new window


0
 
LVL 11

Author Comment

by:Wilder1626
ID: 35003549
Hello all,

I'm coming back again on a way to print a Panel1 that scroll.

How can i do this please?

Thanks
0
 
LVL 11

Author Closing Comment

by:Wilder1626
ID: 35979063
Thanks for your help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now