PrintDialog PrintDialog PrintDialog PrintDialog Class

Definición

Permite a los usuarios seleccionar una impresora y elegir qué secciones del documento para imprimir desde una aplicación de Windows Forms.Lets users select a printer and choose which sections of the document to print from a Windows Forms application.

public ref class PrintDialog sealed : System::Windows::Forms::CommonDialog
public sealed class PrintDialog : System.Windows.Forms.CommonDialog
type PrintDialog = class
    inherit CommonDialog
Public NotInheritable Class PrintDialog
Inherits CommonDialog
Herencia

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar el PrintDialog control para establecer el AllowSomePages, ShowHelp, y Document propiedades.The following code example demonstrates how to use the PrintDialog control to set the AllowSomePages, ShowHelp, and Document properties. Para ejecutar este ejemplo, pegue el código siguiente en un formulario que contenga un PrintDialog control denominado PrintDialog1 y un botón denominado Button1.To run this example, paste the following code into a form that contains a PrintDialog control named PrintDialog1 and a button named Button1. Este ejemplo requiere que el botón Click eventos y el PrintPage eventos de docToPrint se han conectado a los métodos de control de eventos definidos en este ejemplo.This example requires that the button's Click event and the PrintPage event of docToPrint have been connected to the event-handling methods defined in this example.

// Declare the PrintDocument object.
System::Drawing::Printing::PrintDocument^ docToPrint;

// This method will set properties on the PrintDialog object and
// then display the dialog.
void Button1_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
   // Allow the user to choose the page range he or she would
   // like to print.
   PrintDialog1->AllowSomePages = true;
   
   // Show the help button.
   PrintDialog1->ShowHelp = true;
   
   // Set the Document property to the PrintDocument for 
   // which the PrintPage Event has been handled. To display the
   // dialog, either this property or the PrinterSettings property 
   // must be set 
   PrintDialog1->Document = docToPrint;
   if ( docToPrint == nullptr )
         System::Windows::Forms::MessageBox::Show(  "null" );

   ;
   ;
   if ( PrintDialog1 == nullptr )
         System::Windows::Forms::MessageBox::Show(  "pnull" );

   ;
   ;
   System::Windows::Forms::DialogResult result = PrintDialog1->ShowDialog();
   System::Windows::Forms::MessageBox::Show( result.ToString() );
   ;
   ;
   
   // If the result is OK then print the document.
   if ( result == ::DialogResult::OK )
   {
      docToPrint->Print();
   }

}

// The PrintDialog will print the document
// by handling the document's PrintPage event.
void document_PrintPage( Object^ /*sender*/, System::Drawing::Printing::PrintPageEventArgs^ e )
{
   // Insert code to render the page here.
   // This code will be called when the control is drawn.
   // The following code will render a simple
   // message on the printed document.
   String^ text = "In document_PrintPage method.";
   System::Drawing::Font^ printFont = gcnew System::Drawing::Font( "Arial",35,System::Drawing::FontStyle::Regular );
   
   // Draw the content.
   e->Graphics->DrawString( text, printFont, System::Drawing::Brushes::Black, 10, 10 );
}

// Declare the PrintDocument object.
private System.Drawing.Printing.PrintDocument docToPrint = 
	new System.Drawing.Printing.PrintDocument();

// This method will set properties on the PrintDialog object and
// then display the dialog.
private void Button1_Click(System.Object sender, 
	System.EventArgs e)
{

	// Allow the user to choose the page range he or she would
	// like to print.
	PrintDialog1.AllowSomePages = true;

	// Show the help button.
	PrintDialog1.ShowHelp = true;

	// Set the Document property to the PrintDocument for 
	// which the PrintPage Event has been handled. To display the
	// dialog, either this property or the PrinterSettings property 
	// must be set 
	PrintDialog1.Document = docToPrint;

	DialogResult result = PrintDialog1.ShowDialog();

	// If the result is OK then print the document.
	if (result==DialogResult.OK)
	{
		docToPrint.Print();
	}
       
}

// The PrintDialog will print the document
// by handling the document's PrintPage event.
private void document_PrintPage(object sender, 
	System.Drawing.Printing.PrintPageEventArgs e)
{

	// Insert code to render the page here.
	// This code will be called when the control is drawn.

	// The following code will render a simple
	// message on the printed document.
	string text = "In document_PrintPage method.";
	System.Drawing.Font printFont = new System.Drawing.Font
		("Arial", 35, System.Drawing.FontStyle.Regular);

	// Draw the content.
	e.Graphics.DrawString(text, printFont, 
		System.Drawing.Brushes.Black, 10, 10);
}

' Declare the PrintDocument object.
Private WithEvents docToPrint As New Printing.PrintDocument

' This method will set properties on the PrintDialog object and
' then display the dialog.
Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

    ' Allow the user to choose the page range he or she would
    ' like to print.
    PrintDialog1.AllowSomePages = True

    ' Show the help button.
    PrintDialog1.ShowHelp = True

    ' Set the Document property to the PrintDocument for 
    ' which the PrintPage Event has been handled. To display the
    ' dialog, either this property or the PrinterSettings property 
    ' must be set 
    PrintDialog1.Document = docToPrint

    Dim result As DialogResult = PrintDialog1.ShowDialog()

    ' If the result is OK then print the document.
    If (result = DialogResult.OK) Then
        docToPrint.Print()
    End If

End Sub

' The PrintDialog will print the document
' by handling the document's PrintPage event.
Private Sub document_PrintPage(ByVal sender As Object, _
   ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
       Handles docToPrint.PrintPage

    ' Insert code to render the page here.
    ' This code will be called when the control is drawn.

    ' The following code will render a simple
    ' message on the printed document.
    Dim text As String = "In document_PrintPage method."
    Dim printFont As New System.Drawing.Font _
        ("Arial", 35, System.Drawing.FontStyle.Regular)

    ' Draw the content.
    e.Graphics.DrawString(text, printFont, _
        System.Drawing.Brushes.Black, 10, 10)
End Sub

Comentarios

Cuando se crea una instancia de PrintDialog, las propiedades de lectura y escritura se establecen en sus valores iniciales.When you create an instance of PrintDialog, the read/write properties are set to initial values. Para obtener una lista de estos valores, vea el PrintDialog constructor.For a list of these values, see the PrintDialog constructor. Para obtener la configuración de impresora que se modifica por el usuario con el PrintDialog, utilice el PrinterSettings propiedad.To get printer settings that are modified by the user with the PrintDialog, use the PrinterSettings property.

Para obtener más información acerca de la impresión con Windows Forms, consulte el System.Drawing.Printing información general del espacio de nombres.For more information about printing with Windows Forms, see the System.Drawing.Printing namespace overview. Si desea imprimir desde una aplicación de Windows Presentation Foundation, vea el System.Printing espacio de nombres.If you want to print from a Windows Presentation Foundation application, see the System.Printing namespace.

Constructores

PrintDialog() PrintDialog() PrintDialog() PrintDialog()

Inicializa una nueva instancia de la clase PrintDialog.Initializes a new instance of the PrintDialog class.

Propiedades

AllowCurrentPage AllowCurrentPage AllowCurrentPage AllowCurrentPage

Obtiene o establece un valor que indica si se muestra el botón de opción Página actual.Gets or sets a value indicating whether the Current Page option button is displayed.

AllowPrintToFile AllowPrintToFile AllowPrintToFile AllowPrintToFile

Obtiene o establece un valor que indica si la casilla Imprimir a un archivo está habilitada.Gets or sets a value indicating whether the Print to file check box is enabled.

AllowSelection AllowSelection AllowSelection AllowSelection

Obtiene o establece un valor que indica si el botón de opción Selección está habilitado.Gets or sets a value indicating whether the Selection option button is enabled.

AllowSomePages AllowSomePages AllowSomePages AllowSomePages

Obtiene o establece un valor que indica si el botón de opción Páginas está habilitado.Gets or sets a value indicating whether the Pages option button is enabled.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container Container Container Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Document Document Document Document

Obtiene o establece un valor que indica el PrintDocument utilizado para obtener PrinterSettings.Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings.

Events Events Events Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
PrinterSettings PrinterSettings PrinterSettings PrinterSettings

Obtiene o establece la configuración de impresora que se modifica en el cuadro de diálogo.Gets or sets the printer settings the dialog box modifies.

PrintToFile PrintToFile PrintToFile PrintToFile

Obtiene o establece un valor que indica si la casilla Imprimir a un archivo está activada.Gets or sets a value indicating whether the Print to file check box is selected.

ShowHelp ShowHelp ShowHelp ShowHelp

Obtiene o establece un valor que indica si se muestra el botón Ayuda.Gets or sets a value indicating whether the Help button is displayed.

ShowNetwork ShowNetwork ShowNetwork ShowNetwork

Obtiene o establece un valor que indica si se muestra el botón Red.Gets or sets a value indicating whether the Network button is displayed.

Site Site Site Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Inherited from Component)
Tag Tag Tag Tag

Obtiene o establece un objeto que contiene datos sobre el control.Gets or sets an object that contains data about the control.

(Inherited from CommonDialog)
UseEXDialog UseEXDialog UseEXDialog UseEXDialog

Obtiene o establece un valor que indica si el cuadro de diálogo se debería mostrar en el estilo de Windows XP para sistemas que ejecutan Windows XP Home Edition, Windows XP Professional, Windows Server 2003Windows XP Home Edition, Windows XP Professional, Windows Server 2003 o posterior.Gets or sets a value indicating whether the dialog should be shown in the Windows XP style for systems running Windows XP Home Edition, Windows XP Professional, Windows Server 2003Windows XP Home Edition, Windows XP Professional, Windows Server 2003 or later.

Métodos

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos que usa Component.Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa Component y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
HookProc(IntPtr, Int32, IntPtr, IntPtr) HookProc(IntPtr, Int32, IntPtr, IntPtr) HookProc(IntPtr, Int32, IntPtr, IntPtr) HookProc(IntPtr, Int32, IntPtr, IntPtr)

Define el procedimiento de enlace para cuadros de diálogo comunes que se reemplaza para agregar una funcionalidad específica a un cuadro de diálogo común.Defines the common dialog box hook procedure that is overridden to add specific functionality to a common dialog box.

(Inherited from CommonDialog)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnHelpRequest(EventArgs) OnHelpRequest(EventArgs) OnHelpRequest(EventArgs) OnHelpRequest(EventArgs)

Genera el evento HelpRequest.Raises the HelpRequest event.

(Inherited from CommonDialog)
OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr)

Define el procedimiento de ventana propietaria que se reemplaza para agregar una funcionalidad específica a un cuadro de diálogo común.Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.

(Inherited from CommonDialog)
Reset() Reset() Reset() Reset()

Restablece la configuración de página, la última impresora seleccionada y todas las opciones en sus valores predeterminados.Resets all options, the last selected printer, and the page settings to their default values.

RunDialog(IntPtr) RunDialog(IntPtr) RunDialog(IntPtr) RunDialog(IntPtr)

Cuando se reemplaza en una clase derivada, especifica un cuadro de diálogo común.When overridden in a derived class, specifies a common dialog box.

(Inherited from CommonDialog)
ShowDialog() ShowDialog() ShowDialog() ShowDialog()

Ejecuta un cuadro de diálogo común con un propietario predeterminado.Runs a common dialog box with a default owner.

(Inherited from CommonDialog)
ShowDialog(IWin32Window) ShowDialog(IWin32Window) ShowDialog(IWin32Window) ShowDialog(IWin32Window)

Ejecuta un cuadro de diálogo común con el propietario especificado.Runs a common dialog box with the specified owner.

(Inherited from CommonDialog)
ToString() ToString() ToString() ToString()

Devuelve una String que contiene el nombre del Component, si existe.Returns a String containing the name of the Component, if any. Este método no se debe invalidar.This method should not be overridden.

(Inherited from Component)

Eventos

Disposed Disposed Disposed Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
HelpRequest HelpRequest HelpRequest HelpRequest

Se produce cuando el usuario hace clic en el botón Ayuda de un cuadro de diálogo común.Occurs when the user clicks the Help button on a common dialog box.

(Inherited from CommonDialog)

Se aplica a

Consulte también: