多くの場合、ユーザーは印刷先の既定のプリンター以外のプリンターを選択する必要があります。 ユーザーは、 PrintDialog コンポーネントを使用して、現在インストールされているプリンターの中からプリンターを選択できます。 PrintDialog コンポーネントを介して、DialogResult コンポーネントのPrintDialogがキャプチャされ、プリンターの選択に使用されます。
次の手順では、既定のプリンターに印刷するテキスト ファイルを選択します。 その後、 PrintDialog クラスがインスタンス化されます。
プリンターを選択してファイルを印刷するには
PrintDialog コンポーネントを使用して使用するプリンターを選択します。
次のコード例では、2 つのイベントが処理されています。 最初の Button コントロールの Click イベントでは、 PrintDialog クラスがインスタンス化され、ユーザーによって選択されたプリンターが DialogResult プロパティにキャプチャされます。
2番目のイベントでは、PrintPageコンポーネントのPrintDocumentイベントは、指定されたプリンタにサンプルドキュメントが印刷される。
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim PrintDialog1 As New PrintDialog() PrintDialog1.Document = PrintDocument1 Dim result As DialogResult = PrintDialog1.ShowDialog() If (result = DialogResult.OK) Then PrintDocument1.Print() End If End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage e.Graphics.FillRectangle(Brushes.Red, New Rectangle(500, 500, 500, 500)) End Sub
private void button1_Click(object sender, System.EventArgs e) { PrintDialog printDialog1 = new PrintDialog(); printDialog1.Document = printDocument1; DialogResult result = printDialog1.ShowDialog(); if (result == DialogResult.OK) { printDocument1.Print(); } } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { e.Graphics.FillRectangle(Brushes.Red, new Rectangle(500, 500, 500, 500)); }
private: void button1_Click(System::Object ^ sender, System::EventArgs ^ e) { PrintDialog ^ printDialog1 = gcnew PrintDialog(); printDialog1->Document = printDocument1; System::Windows::Forms::DialogResult result = printDialog1->ShowDialog(); if (result == DialogResult::OK) { printDocument1->Print(); } } private: void printDocument1_PrintPage(System::Object ^ sender, System::Drawing::Printing::PrintPageEventArgs ^ e) { e->Graphics->FillRectangle(Brushes::Red, Rectangle(500, 500, 500, 500)); }
(Visual C# と Visual C++)フォームのコンストラクターに次のコードを配置して、イベント ハンドラーを登録します。
this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler (this.printDocument1_PrintPage); this.button1.Click += new System.EventHandler(this.button1_Click);
this->printDocument1->PrintPage += gcnew System::Drawing::Printing::PrintPageEventHandler (this, &Form1::printDocument1_PrintPage); this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
こちらも参照ください
.NET Desktop feedback