Cómo imprimir los formularios Windows Forms activos en Visual Basic .NET| Id. de artículo | : | 890894 | | Última revisión | : | jueves, 31 de mayo de 2007 | | Versión | : | 2.3 |
INTRODUCCIÓNEn este artículo se describe cómo imprimir los formularios Windows Forms activos en Microsoft Visual Basic .NET Visual Basic utilizando funciones interfaz de dispositivo de gráficos Windows (GDI). Volver al principio
Más informaciónPara imprimir el formulario activo Windows Forms en Visual Basic .NET, debe hacer lo siguiente: | 1. | Cree un objeto PrintDocument para enviar resultado a la impresora. | | 2. | Cree una clase que contiene las estructuras GDI de Windows y las instrucciones DllImport que requieren llamar a las funciones GDI de Windows. | | 3. | Asocie el evento PrintDocument.PrintPage a un controlador de eventos que se denomina OnPrintPage. Para ello, utilice la instrucción AddHandler. | | 4. | En el controlador de eventos OnPrintPage, imprima el contexto actual de dispositivo de Windows como una imagen gráfica al objeto PrintDocument cuando se llama al método PrintDocument.Print. |
Para ello, siga estos pasos: | 1. | En Microsoft Visual Studio .NET 2003, cree una aplicación de Windows de Visual Basic nueva. | | 2. | Agregue dos o árbol de controles de Formularios Windows Forms a Form1.vb. Por ejemplo, agregue un control TextBox, un control CheckBox y un control Button al formulario. | | 3. | Haga clic en el control Button1 y cambie la propiedad Texto por a Print En la ventana Propiedades. | | 4. | En Explorador de soluciones, haga clic con el botón secundario en Form1.vb y a continuación, haga clic en Ver código. | | 5. | Agregue la siguiente instrucción Imports al principio del código fuente Form1.vb: Imports System.Drawing.Printing
Imports System.Drawing.Graphics
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices Nota Este paso agrega las referencias requeridas que denomina las referencias la impresión, el gráfico, el Imaging, las funciones InteropServices y los métodos. | | 6. | Agregue la clase siguiente Win32APICall a Form1.vb después de la clase Form1:Public Class Win32APICall
Public Const DIB_RGB_COLORS = 0
Public Const BI_RGB = 0
Public Const WHITENESS = 16711778
<DllImport("user32.dll", EntryPoint:="PrintWindow", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function PrintWindow(ByVal hWnd As IntPtr, ByVal hDC As IntPtr, ByVal dwFlags As Integer) As UInt32
End Function
<StructLayout(LayoutKind.Sequential, pack:=8, CharSet:=CharSet.Auto)> _
Structure BITMAPINFOHEADER
Dim biSize As Int32
Dim biWidth As Int32
Dim biHeight As Int32
Dim biPlanes As Int16
Dim biBitCount As Int16
Dim biCompression As Int32
Dim biSizeImage As Int32
Dim biXPelsPerMeter As Int32
Dim biYPelsPerMeter As Int32
Dim biClrUsed As Int32
Dim biClrImportant As Int32
End Structure
<DllImport("gdi32.dll", EntryPoint:="CreateDIBSection", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function CreateDIBSection(ByVal hdc As IntPtr, ByRef pbmi As BITMAPINFOHEADER, _
ByVal iUsage As Int32, ByVal ppvBits As IntPtr, ByVal hSection As IntPtr, _
ByVal dwOffset As Int32) As IntPtr
End Function
<DllImport("gdi32.dll", EntryPoint:="PatBlt", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function PatBlt(ByVal hDC As IntPtr, ByVal nXLeft As Int32, _
ByVal nYLeft As Int32, ByVal nWidth As Int32, ByVal nHeight As Int32, _
ByVal dwRop As Int32) As Boolean
End Function
<DllImport("gdi32.dll", EntryPoint:="SelectObject", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function SelectObject(ByVal hDC As IntPtr, ByVal hObj As IntPtr) As IntPtr
End Function
<DllImport("GDI32.dll", EntryPoint:="CreateCompatibleDC", SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function CreateCompatibleDC(ByVal hRefDC As IntPtr) As IntPtr
End Function
<DllImport("GDI32.dll", EntryPoint:="DeleteDC", SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function DeleteDC(ByVal hDC As IntPtr) As Boolean
End Function
<DllImport("GDI32.dll", EntryPoint:="DeleteObject", SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function DeleteObject(ByVal hObj As IntPtr) As Boolean
End Function
<DllImport("User32.dll", EntryPoint:="ReleaseDC", SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function ReleaseDC(ByVal hWnd As IntPtr, ByVal hDC As IntPtr) As Boolean
End Function
<DllImport("User32.dll", EntryPoint:="GetDC", SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function GetDC(ByVal hWnd As IntPtr) As IntPtr
End Function
End ClassNota Este paso agrega las variables, las estructuras y las instrucciones DllImport que requieren llamar a funciones API de GDI de Windows no administradas. | | 7. | Agregue el procedimiento controlador siguiente de evento OnPrintPage al código fuente Form1.vb en la clase Form1: Private Sub OnPrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim hwndForm As IntPtr
hwndForm = Me.Handle
Dim hdcDIBSection As IntPtr
Dim hdcRef As IntPtr
Dim hbmDIBSection As IntPtr
Dim hbmDIBSectionOld As IntPtr
Dim BMPheader As Win32APICall.BITMAPINFOHEADER
hdcRef = Win32APICall.GetDC(IntPtr.Zero)
hdcDIBSection = Win32APICall.CreateCompatibleDC(hdcRef)
Win32APICall.ReleaseDC(IntPtr.Zero, hdcRef)
BMPheader.biBitCount = 24
BMPheader.biClrImportant = 0
BMPheader.biClrUsed = 0
BMPheader.biCompression = Win32APICall.BI_RGB
BMPheader.biSize = 40
BMPheader.biHeight = Me.Height
BMPheader.biPlanes = 1
BMPheader.biSizeImage = 0
BMPheader.biWidth = Me.Width
BMPheader.biXPelsPerMeter = 0
BMPheader.biYPelsPerMeter = 0
hbmDIBSection = Win32APICall.CreateDIBSection(hdcDIBSection, BMPheader, Win32APICall.DIB_RGB_COLORS, _
IntPtr.Zero, IntPtr.Zero, 0)
hbmDIBSectionOld = Win32APICall.SelectObject(hdcDIBSection, hbmDIBSection)
Win32APICall.PatBlt(hdcDIBSection, 0, 0, Me.Width, Me.Height, Win32APICall.WHITENESS)
Win32APICall.PrintWindow(hwndForm, hdcDIBSection, 0)
Win32APICall.SelectObject(hdcDIBSection, hbmDIBSectionOld)
Dim imageFrm As Bitmap
imageFrm = Image.FromHbitmap(hbmDIBSection)
e.Graphics.DrawImage(imageFrm, 0, 0)
Win32APICall.DeleteDC(hdcDIBSection)
Win32APICall.DeleteObject(hbmDIBSection)
End Sub
End ClassNota Este controlador de eventos se ejecutará cuando se ejecuta el método PrintDocument.Print. | | 8. | Agregue el código siguiente al evento Click para el botón Imprimir que fue creado por usted en paso 2 en la clase Form1: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim prd As PrintDocument
prd = New PrintDocument
AddHandler prd.PrintPage, AddressOf OnPrintPage
prd.Print()
End SubNota Este paso agrega el código que se ejecuta cuando hace clic en el botón Imprimir. El código declara un objeto PrintDocument en primer lugar. A continuación, el código agrega un controlador de eventos utilizando la instrucción AddHandler. Este controlador de eventos se ejecuta cuando se llama al método PrintDocument.Print. | | 9. | Presione CTRL-F5 para ejecutar la solución y a continuación, hacer clic en Imprimir para imprimir el formulario actual Windows Forms. |
Volver al principio
ReferenciasPara obtener más información, visite los siguientes sitios Web de Microsoft Developer Network (MSDN) Volver al principio
La información de este artículo se refiere a:| ? | Microsoft Visual Studio .NET 2003 Professional Edition | | ? | Microsoft Visual Studio .NET 2003 Enterprise Architect | | ? | Microsoft Visual Studio .NET 2003 Enterprise Developer | | ? | Microsoft Visual Studio .NET 2003 Academic Edition |
Volver al principio
IMPORTANTE: Este artículo ha sido traducido por un software de traducción automática de Microsoft (http://support.microsoft.com/gp/mtdetails) en lugar de un traductor humano. Microsoft le ofrece artículos traducidos por un traductor humano y artículos traducidos automáticamente para que tenga acceso en su propio idioma a todos los artículos de nuestra base de conocimientos (Knowledge Base). Sin embargo, los artículos traducidos automáticamente pueden contener errores en el vocabulario, la sintaxis o la gramática, como los que un extranjero podría cometer al hablar el idioma. Microsoft no se hace responsable de cualquier imprecisión, error o daño ocasionado por una mala traducción del contenido o como consecuencia de su utilización por nuestros clientes. Microsoft suele actualizar el software de traducción frecuentemente. Si ve errores y desea ayudar con este esfuerzo, rellene la encuesta en la parte inferior de este artículo.Haga clic aquí para ver el artículo original (en inglés): 890894 (http://support.microsoft.com/kb/890894/en-us/) Volver al principio
| Other Support Options- Need More Help?
Contact a Support professional by E-mail, Online or Phone. - Customer Service
For non-technical assistance with product purchases, subscriptions, online services, events, training courses, corporate sales, piracy issues, and more. - Newsgroups
Pose a question to other users. Discussion groups and Forums about specific Microsoft products, technologies, and services.
|
|