Windows forms print preview

Практическое руководство. Печать в Windows Forms с использованием предварительного просмотра How to: Print in Windows Forms Using Print Preview

При программировании с использованием Windows Forms в качестве дополнения к службам печати часто предлагается возможность предварительного просмотра. It is very common in Windows Forms programming to offer print preview in addition to printing services. Легким способом добавления предварительного просмотра в приложение является использование элемента управления PrintPreviewDialog в сочетании с логикой обработки событий PrintPage для печати файла. An easy way to add print preview services to your application is to use a PrintPreviewDialog control in combination with the PrintPage event-handling logic for printing a file.

Предварительный просмотр текстового документа с помощью элемента управления PrintPreviewDialog To preview a text document with a PrintPreviewDialog control

Добавьте в форму элемент управления PrintPreviewDialog, PrintDocumentи две строки. Add a PrintPreviewDialog, PrintDocument, and two strings to your form.

Укажите в качестве значения свойства DocumentName документ, который нужно напечатать, а затем откройте документ и прочтите его содержимое в строку, добавленную ранее. Set the DocumentName property to the document you wish to print, and open and read the document’s contents to the string you added previously.

Как и при печати документа, для расчета числа строк на странице и отрисовки содержимого документа в обработчике событий PrintPage используется свойство Graphics класса PrintPageEventArgs и содержимое файла. As you would for printing the document, in the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the file contents to calculate lines per page and render the document’s contents. Нарисовав очередную страницу, проверьте, является ли она последней, и установите соответствующим образом свойство HasMorePages класса PrintPageEventArgs . After each page is drawn, check to see if it is the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. Событие PrintPage возникает до тех пор, пока значение свойства HasMorePages не станет равно false . The PrintPage event is raised until HasMorePages is false . После завершения отрисовки документа сбросьте строку, подлежащую отрисовке. When the document has finished rendering, reset the string to be rendered. Кроме того, убедитесь в том, что событие PrintPage связано со своим методом обработки событий. Also, make sure the PrintPage event is associated with its event-handling method.

Если поддержка печати уже реализована в приложении, то, возможно, шаги 2 и 3 были выполнены ранее. You may have already completed steps 2 and 3 if you have implemented printing in your application.

В примере кода ниже обработчик событий используется для печати файла testPage.txt тем шрифтом, который используется в форме. In the following code example, the event handler is used to print the «testPage.txt» file in the same font used on the form.

Присвойте свойству Document элемента управления PrintPreviewDialog значение компонента PrintDocument в форме. Set the Document property of the PrintPreviewDialog control to the PrintDocument component on the form.

Читайте также:  Как разогнать компьютера windows 10

Вызовите метод ShowDialog элемента управления PrintPreviewDialog . Call the ShowDialog method on the PrintPreviewDialog control. Как правило, метод ShowDialog вызывается из метода обработки событий Click кнопки. You would typically call ShowDialog from the Click event-handling method of a button. Вызов метода ShowDialog приводит к возникновению события PrintPage и отрисовке выходных данных в элементе управления PrintPreviewDialog . Calling ShowDialog raises the PrintPage event and renders the output to the PrintPreviewDialog control. Когда пользователь нажимает на значок печати в диалоговом окне, событие PrintPage вызывается снова. При этом выходные данные отправляются на принтер, а не в диалоговое окно предварительного просмотра. When the user clicks the print icon on the dialog, the PrintPage event is raised again, sending the output to the printer instead of the preview dialog. Вот почему в шаге 3 в конце процесса отрисовки сбрасывалась строка. This is why the string is reset at the end of the rendering process in step 3.

В примере ниже показан метод обработки событий Click для кнопки в форме. The following code example shows the Click event-handling method for a button on the form. Этот метод вызывает методы для чтения документа и вывода окна предварительного просмотра. This event-handling method calls the methods to read the document and show the print preview dialog.

Пример Example

Компиляция кода Compiling the Code

Для этого примера требуются: This example requires:

How to: Print in Windows Forms Using Print Preview

It is very common in Windows Forms programming to offer print preview in addition to printing services. An easy way to add print preview services to your application is to use a PrintPreviewDialog control in combination with the PrintPage event-handling logic for printing a file.

To preview a text document with a PrintPreviewDialog control

Add a PrintPreviewDialog, PrintDocument, and two strings to your form.

Set the DocumentName property to the document you wish to print, and open and read the document’s contents to the string you added previously.

As you would for printing the document, in the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the file contents to calculate lines per page and render the document’s contents. After each page is drawn, check to see if it is the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. The PrintPage event is raised until HasMorePages is false . When the document has finished rendering, reset the string to be rendered. Also, make sure the PrintPage event is associated with its event-handling method.

You may have already completed steps 2 and 3 if you have implemented printing in your application.

In the following code example, the event handler is used to print the «testPage.txt» file in the same font used on the form.

Set the Document property of the PrintPreviewDialog control to the PrintDocument component on the form.

Call the ShowDialog method on the PrintPreviewDialog control. You would typically call ShowDialog from the Click event-handling method of a button. Calling ShowDialog raises the PrintPage event and renders the output to the PrintPreviewDialog control. When the user clicks the print icon on the dialog, the PrintPage event is raised again, sending the output to the printer instead of the preview dialog. This is why the string is reset at the end of the rendering process in step 3.

The following code example shows the Click event-handling method for a button on the form. This event-handling method calls the methods to read the document and show the print preview dialog.

How to: Display Print Preview in Windows Forms Applications

You can use the PrintPreviewDialog control to enable users to display a document, often before it is to be printed.

Читайте также:  Не выключается монитор при выключении компьютера windows 10

To do this, you need to specify an instance of the PrintDocument class; this is the document to be printed. For more information about using print preview with the PrintDocument component, see How to: Print in Windows Forms Using Print Preview.

To use the PrintPreviewDialog control at run time, users must have a printer installed on their computer, either locally or through a network, as this is partly how the PrintPreviewDialog component determines how a document will look when printed.

The PrintPreviewDialog control uses the PrinterSettings class. Additionally, the PrintPreviewDialog control uses the PageSettings class, just as the PrintPreviewDialog component does. The print document specified in the PrintPreviewDialog control’s Document property refers to instances of both the PrinterSettings and PageSettings classes, and these are used to render the document in the preview window.

To view pages using the PrintPreviewDialog control

Use the ShowDialog method to display the dialog box, specifying the PrintDocument to use.

In the following code example, the Button control’s Click event handler opens an instance of the PrintPreviewDialog control. The print document is specified in the Document property. In the example below, no print document is specified.

The example requires that your form has a Button control, a PrintDocument component named myDocument , and a PrintPreviewDialog control.

(Visual C#, Visual C++) Place the following code in the form’s constructor to register the event handler.

Практическое руководство. Предварительный просмотр при печати в приложениях Windows Forms How to: Display Print Preview in Windows Forms Applications

Элемент управления можно использовать PrintPreviewDialog для предоставления пользователям возможности отображать документ, часто перед его печатью. You can use the PrintPreviewDialog control to enable users to display a document, often before it is to be printed.

Для этого необходимо указать экземпляр PrintDocument класса; это документ для печати. To do this, you need to specify an instance of the PrintDocument class; this is the document to be printed. Дополнительные сведения об использовании предварительного просмотра с PrintDocument компонентом см. в разделе инструкции. печать в Windows Forms с помощью предварительного просмотра. For more information about using print preview with the PrintDocument component, see How to: Print in Windows Forms Using Print Preview.

Чтобы использовать PrintPreviewDialog элемент управления во время выполнения, на компьютере пользователя должен быть установлен принтер (локально или через сеть), поскольку он частично определяет, как именно этот PrintPreviewDialog документ будет выглядеть при печати. To use the PrintPreviewDialog control at run time, users must have a printer installed on their computer, either locally or through a network, as this is partly how the PrintPreviewDialog component determines how a document will look when printed.

PrintPreviewDialogЭлемент управления использует PrinterSettings класс. The PrintPreviewDialog control uses the PrinterSettings class. Кроме того, PrintPreviewDialog элемент управления использует PageSettings класс так же, как и PrintPreviewDialog компонент. Additionally, the PrintPreviewDialog control uses the PageSettings class, just as the PrintPreviewDialog component does. Документ печати, указанный в PrintPreviewDialog Document свойстве элемента управления, относится к экземплярам PrinterSettings классов и и PageSettings используется для отрисовки документа в окне предварительного просмотра. The print document specified in the PrintPreviewDialog control’s Document property refers to instances of both the PrinterSettings and PageSettings classes, and these are used to render the document in the preview window.

Просмотр страниц с помощью элемента управления PrintPreviewDialog To view pages using the PrintPreviewDialog control

Используйте метод ShowDialog для отображения диалогового окна, указав используемый PrintDocument . Use the ShowDialog method to display the dialog box, specifying the PrintDocument to use.

Читайте также:  Linux installation from usb

В следующем примере кода Button Click обработчик событий элемента управления открывает экземпляр PrintPreviewDialog элемента управления. In the following code example, the Button control’s Click event handler opens an instance of the PrintPreviewDialog control. Документ печати задается в Document свойстве. The print document is specified in the Document property. В приведенном ниже примере не указан документ Print. In the example below, no print document is specified.

В примере требуется, чтобы форма соработала Button элемент управления, PrintDocument компонент с именем myDocument и PrintPreviewDialog элемент управления. The example requires that your form has a Button control, a PrintDocument component named myDocument , and a PrintPreviewDialog control.

(Visual C#, Visual C++) Поместите следующий код в конструктор формы для регистрации обработчика событий. (Visual C#, Visual C++) Place the following code in the form’s constructor to register the event handler.

Поддержка печати в Windows Forms Windows Forms Print Support

Печать в Windows Forms состоит в основном с использованием компонента PrintDocument , который позволяет пользователю печатать, и компоненты элемента управления PrintPreviewDialog , компонента PrintDialog и компонента PageSetupDialog , чтобы обеспечить знакомый графический интерфейс для пользователей, привыкших к операционной системе Windows. Printing in Windows Forms consists primarily of using the PrintDocument Component component to enable the user to print, and the PrintPreviewDialog Control control, PrintDialog Component and PageSetupDialog Component components to provide a familiar graphical interface to users accustomed to the Windows operating system.

Как правило, создается новый экземпляр PrintDocument компонента, устанавливаются свойства, описывающие, что печатать с помощью PrinterSettings PageSettings классов и, и вызывается Print метод для фактической печати документа. Typically, you create a new instance of the PrintDocument component, set the properties that describe what to print using the PrinterSettings and PageSettings classes, and call the Print method to actually print the document.

Во время печати из приложения Windows PrintDocument компонент покажет диалоговое окно «Прервать печать», чтобы предупредить пользователей о том, что происходит печать, и разрешить отмену задания печати. During the course of printing from a Windows-based application, the PrintDocument component will show an abort print dialog box to alert users to the fact that printing is occurring and to allow the print job to be canceled.

в этом разделе In This Section

Практическое руководство. Создание стандартных задания печати в Windows Forms How to: Create Standard Windows Forms Print Jobs
Объясняет, как использовать PrintDocument компонент для печати из формы Windows Forms. Explains how to use the PrintDocument component to print from a Windows Form.

Практическое руководство. Перенаправление данных, введенных пользователем в PrintDialog во время выполнения How to: Capture User Input from a PrintDialog at Run Time
Объясняет, как программно изменить выбранные параметры печати с помощью PrintDialog компонента. Explains how to modify selected print options programmatically using the PrintDialog component.

Практическое руководство. Выбор принтера, подключенного к компьютеру пользователя, в Windows Forms How to: Choose the Printers Attached to a User’s Computer in Windows Forms
Описывает изменение принтера для печати на использование PrintDialog компонента во время выполнения. Describes changing the printer to print to using the PrintDialog component at run time.

Практическое руководство. Выполнение заданий печати в Windows Forms How to: Complete Windows Forms Print Jobs
Объясняет, как предупредить пользователей о завершении задания печати. Explains how to alert users to the completion of a print job.

Практическое руководство. Печать формы Windows Forms How to: Print a Windows Form
Показывает, как распечатать копию текущей формы. Shows how to print a copy of the current form.

Компонент PrintDialog PrintDialog Component
Объясняет использование PrintDialog компонента. Explains usage of the PrintDialog component.

Оцените статью
Добавить комментарий

Adblock
detector