Below is a sample class that will let you do this. For example, if you have a CWGraph on the form called AxCWGraph1, you could print it with the code below like this:
Dim printer As ControlPrinter = New ControlPrinter(AxCWGraph1)
printer.Print()
To use this, create a new class in your project and copy and paste the code below into it.
Hope this helps,
- Elton
Imports System
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Public Class ControlPrinter
Implements IDisposable
Private target As Control
Private document As PrintDocument
Private dialog As PrintDialog
_
Private Shared Function BitBlt( _
ByVal hdcDest As IntPtr, _
ByVal nXDest As Integer, _
ByVal nYDest As Integer, _
ByVal nWidth As Integer, _
ByVal nHeight As Integer, _
ByVal hdcSrc As IntPtr, _
ByVal nXSrc As Integer, _
ByVal nYSrc As Integer, _
ByVal dwRop As Integer _
) As Boolean
End Function
Private Shared SRCCOPY As Integer = &HCC0020
Public Sub New(ByVal printTarget As Control)
If printTarget Is Nothing Then
Throw New ArgumentNullException("printTarget")
End If
target = printTarget
document = New PrintDocument()
dialog = New PrintDialog()
AddHandler document.PrintPage, AddressOf OnPrintPage
dialog.Document = document
End Sub
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not document Is Nothing Then
document.Dispose()
End If
If Not dialog Is Nothing Then
dialog.Dispose()
End If
End If
End Sub
Protected Overrides Sub Finalize()
Try
Dispose(False)
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Print()
If dialog.ShowDialog() = DialogResult.OK Then
document.Print()
End If
End Sub
Private Sub OnPrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
Dim controlGraphics As Graphics = target.CreateGraphics()
Dim controlImage As Image = New Bitmap(target.Size.Width, target.Size.Height, controlGraphics)
Dim buffer As Graphics = Graphics.FromImage(controlImage)
Dim controlDC As IntPtr = controlGraphics.GetHdc()
Dim bufferDC As IntPtr = buffer.GetHdc()
BitBlt(bufferDC, 0, 0, target.Width, target.Height, controlDC, 0, 0, SRCCOPY)
controlGraphics.ReleaseHdc(controlDC)
buffer.ReleaseHdc(bufferDC)
e.Graphics.DrawImage(controlImage, 0, 0)
buffer.Dispose()
controlImage.Dispose()
End Sub
End Class