Infragistics 製品にはバーコードやQRコードを生成することのできるコントロールが含まれています。 Windows Forms 版には専用の UltraBarcode コントロール( UltraCode128Barcode や UltraQRCodeBarcode )がございますが、プリンターでの印刷の際にはフォームに表示されている時と比べて若干鮮明度が劣るようです。一方、 WPF 版の XamBarcode コントロールは印刷時も鮮明度が保たれます。そこで、今回は Windows Forms アプリケーションで ElementHost コントロールによってWPFコントロールであるXamBarcodeをホストし、印刷する方法をご紹介します。
Windows Forms で WPF コントロールをホストするために、まずは Windows Forms のソリューションに新規ライブラリとして「WPFユーザーコントロールライブラリ」を追加します。デフォルトの名前( WpfControlLibrary1 )のままライブラリを追加しますと、Visual Studio のソリューションエクスプローラは以下のような表示となります。
WPF のマークアップファイルである UserControl1.xaml が自動的に追加されています。
このファイルに、XamBarcode コントロールを配置していきます。
WpfControlLibrary1 プロジェクトの参照設定に、以下の3つの Infragistics アセンブリを追加し、
InfragisticsWPF4.Controls.Barcodes
InfragisticsWPF4.DataVisualization
InfragisticsWPF4
UserControl1.xaml には以下を追加して XamBarcode コントロールの配置を行います。
<ig:XamCode128Barcode x:Name="myBarcode" Data="test code" CodeType="Standard"/>
今回は XamCode128Barcode を使用しました。コードのデータは ”test code” としました。Visual Studio のデザイナ画面にバーコードが表示されていることをご確認ください。
次に、このユーザーコントロールを Windows Forms に追加します。
Form1.cs のデザイナ画面を開き、ツールボックスから先ほど作成した UserControl をフォーム上へドラッグドロップしてください。これにより、WPF コントロールをホストするための ElementHost は自動的に生成されます。
さらに、印刷処理実行用にボタンをフォームに追加しておいてください。
ここからは印刷処理の実装です。
バーコードコントロールを印刷するには、バーコードの画像データを一旦 Image インスタンスにしてからPrintDocumentを使用して画像の印刷を行います。
変数として Image インスタンスを以下のように宣言してから、
private Image image;
フォームに追加しておいたボタンの Click イベントを以下のように実装します。
private void button1_Click(object sender, EventArgs e)
{
XamCode128Barcode codeToPrint =
(elementHost1.Child as UserControl1).FindName("myBarcode") as XamCode128Barcode;
int height = Convert.ToInt32(codeToPrint.ActualHeight);
int width = Convert.ToInt32(codeToPrint.ActualWidth);
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
renderTargetBitmap.Render(codeToPrint);
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
encoder.Save(outStream);
this.image = new System.Drawing.Bitmap(outStream);
}
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += PrintDocument_PrintPage;
printDocument.Print();
}
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(this.image, new Point(0, 0));
e.HasMorePages = false;
}
UserControl 上の XamCode128Barcode へは、ElementHost の Child から FindName() メソッドを使用してアクセスします。ここでも XamCode128Barcode を参照しますので、必要な Infragistics アセンブリをプロジェクトの参照設定に追加してください。
アプリケーションを実行してみます。
XamBarcode コントロールが Windows Forms のフォームに表示されました。
ボタンのクリックでバーコードが印刷されます。
今回のサンプルはこちらからダウンロードいただけます。
(当サンプルは16.2.20162.1006バージョンを使用して作成されました)
最後までお読みくださり、ありがとうございました。