PrintDialog Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Позволяет пользователям выбирать принтер и выбирать разделы документа для печати из приложения Windows Forms.
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
- Наследование
Примеры
В следующем примере кода показано, как использовать PrintDialog элемент управления для задания AllowSomePagesShowHelpсвойств и Document свойств. Чтобы запустить этот пример, вставьте следующий код в форму, содержащую PrintDialog элемент управления с именем и кнопкой с именемButton1PrintDialog1. В этом примере требуется, чтобы событие кнопки Click и PrintPage событие docToPrint были подключены к методам обработки событий, определенным в этом примере.
// 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
Комментарии
При создании экземпляра свойства чтения и записи задаются для начальных PrintDialogзначений. Список этих значений см. в конструкторе PrintDialog . Чтобы получить параметры принтера, измененные пользователем с PrintDialogпомощью свойства, используйте PrinterSettings это свойство.
Дополнительные сведения о печати с помощью Windows Forms см. в обзоре System.Drawing.Printing пространства имен. Если вы хотите распечатать из приложения Windows Presentation Foundation, просмотрите System.Printing пространство имен.
Конструкторы
| Имя | Описание |
|---|---|
| PrintDialog() |
Инициализирует новый экземпляр класса PrintDialog. |
Свойства
| Имя | Описание |
|---|---|
| AllowCurrentPage |
Возвращает или задает значение, указывающее, отображается ли кнопка " Текущая страница ". |
| AllowPrintToFile |
Возвращает или задает значение, указывающее, включен ли флажок "Печать в файл ". |
| AllowSelection |
Возвращает или задает значение, указывающее, включена ли кнопка выбора . |
| AllowSomePages |
Возвращает или задает значение, указывающее, включена ли кнопка параметра Pages . |
| CanRaiseEvents |
Возвращает значение, указывающее, может ли компонент вызвать событие. (Унаследовано от Component) |
| Container |
Возвращает объект IContainer , содержащий Componentобъект . (Унаследовано от Component) |
| DesignMode |
Возвращает значение, указывающее, находится ли текущий Component режим разработки. (Унаследовано от Component) |
| Document |
Возвращает или задает значение, указывающее используемое PrintDocument для получения PrinterSettings. |
| Events |
Возвращает список обработчиков событий, подключенных к этому Component. (Унаследовано от Component) |
| PrinterSettings |
Возвращает или задает параметры принтера, которые изменяет диалоговое окно. |
| PrintToFile |
Возвращает или задает значение, указывающее, установлен ли флажок "Печать в файл ". |
| ShowHelp |
Возвращает или задает значение, указывающее, отображается ли кнопка справки . |
| ShowNetwork |
Возвращает или задает значение, указывающее, отображается ли кнопка "Сеть ". |
| Site |
Возвращает или задает ISite объект Component. (Унаследовано от Component) |
| Tag |
Возвращает или задает объект, содержащий данные об элементе управления. (Унаследовано от CommonDialog) |
| UseEXDialog |
Возвращает или задает значение, указывающее, следует ли отображать диалоговое окно в стиле Windows XP для систем под управлением Windows XP Home Edition, Windows XP Professional, Windows Server 2003 или более поздней версии. |
Методы
| Имя | Описание |
|---|---|
| CreateObjRef(Type) |
Создает объект, содержащий все соответствующие сведения, необходимые для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. (Унаследовано от MarshalByRefObject) |
| Dispose() |
Освобождает все ресурсы, используемые параметром Component. (Унаследовано от Component) |
| Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые Component и при необходимости освобождает управляемые ресурсы. (Унаследовано от Component) |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetLifetimeService() |
Устаревшие..
Извлекает текущий объект службы времени существования, который управляет политикой времени существования для этого экземпляра. (Унаследовано от MarshalByRefObject) |
| GetService(Type) |
Возвращает объект, представляющий службу, предоставляемую Component или ее Container. (Унаследовано от Component) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| HookProc(IntPtr, Int32, IntPtr, IntPtr) |
Определяет общую процедуру перехватчика диалогового окна, переопределенную для добавления определенных функций в общее диалоговое окно. (Унаследовано от CommonDialog) |
| InitializeLifetimeService() |
Устаревшие..
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. (Унаследовано от MarshalByRefObject) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| MemberwiseClone(Boolean) |
Создает неглубокую копию текущего MarshalByRefObject объекта. (Унаследовано от MarshalByRefObject) |
| OnHelpRequest(EventArgs) |
Вызывает событие HelpRequest. (Унаследовано от CommonDialog) |
| OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr) |
Определяет процедуру окна владельца, переопределенную для добавления определенных функций в общее диалоговое окно. (Унаследовано от CommonDialog) |
| Reset() |
Сбрасывает все параметры, последний выбранный принтер и параметры страницы в значения по умолчанию. |
| RunDialog(IntPtr) |
При переопределении в производном классе задает общее диалоговое окно. (Унаследовано от CommonDialog) |
| ShowDialog() |
Запускает общее диалоговое окно с владельцем по умолчанию. (Унаследовано от CommonDialog) |
| ShowDialog(IWin32Window) |
Запускает общее диалоговое окно с указанным владельцем. (Унаследовано от CommonDialog) |
| ToString() |
String Возвращает имя, содержащее имя , если таковое Componentимеется. Этот метод не должен быть переопределен. (Унаследовано от Component) |
События
| Имя | Описание |
|---|---|
| Disposed |
Происходит при удалении компонента вызовом Dispose() метода. (Унаследовано от Component) |
| HelpRequest |
Происходит, когда пользователь нажимает кнопку справки в общем диалоговом окне. (Унаследовано от CommonDialog) |