반응형
찰스 페졸드의 WPF 를 읽으면서 정리한 인쇄(PrintaBunchaButtons) 소스.
UIElement에서 파생된 클래스 인스턴스를 인쇄할 때 중요한 단계가 필요하며, 엘리먼트를 배치하기 위해 객체의 Measure와 Arrange 메소드를 호출해야 한다.
Arrange 메소드 호출 후에 UIElement의 InvalidateArrange 메서드를 호출해야 인쇄 시 정상적으로 표시가 된다.
[PrintaBunchaButtons.cs 파일]
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace PrintaBunchaButtons
{
public class PrintaBunchaButtons : Window
{
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new PrintaBunchaButtons());
}
public PrintaBunchaButtons()
{
Title = "Print a Bunch of Buttons";
SizeToContent = SizeToContent.WidthAndHeight;
ResizeMode = ResizeMode.CanMinimize;
//Print 버튼 생성
Button btn = new Button();
btn.FontSize = 24;
btn.Content = "Print ...";
btn.Padding = new Thickness(12);
btn.Margin = new Thickness(96);
btn.Click += PrintOnClick;
Content = btn;
}
private void PrintOnClick(object sender, RoutedEventArgs e)
{
PrintDialog dlg = new PrintDialog();
if ((bool)dlg.ShowDialog().GetValueOrDefault())
{
//그리드 패널 생성
Grid grid = new Grid();
//자동으로 크기가 변하는 열과 행을 5개 정의
for (int i = 0; i < 5; i++)
{
ColumnDefinition colDef = new ColumnDefinition();
colDef.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(colDef);
RowDefinition rowDef = new RowDefinition();
rowDef.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowDef);
}
//그라디언트 브러시로 그리드의 배경색을 지정
grid.Background = new LinearGradientBrush(Colors.Gray, Colors.White,
new Point(0, 0), new Point(1, 1));
//난수 생성
Random rand = new Random();
//25개 버튼으로 Grid를 채움
for (int i = 0; i < 25; i++)
{
Button btn = new Button();
btn.FontSize = 12 + rand.Next(8);
btn.Content = "Button No. " + (i + 1);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = VerticalAlignment.Center;
btn.Margin = new Thickness(6);
grid.Children.Add(btn);
Grid.SetRow(btn, i % 5);
Grid.SetColumn(btn, i / 5);
}
//그리드 크기 결정
grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Size sizeGrid = grid.DesiredSize;
//페이지상의 그리드의 중앙점을 결정
Point ptGrid = new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2,
(dlg.PrintableAreaHeight - sizeGrid.Height) / 2);
//레이아웃은 설정하지 않고 통과
grid.Arrange(new Rect(ptGrid, sizeGrid));
grid.InvalidateArrange();
//인쇄
dlg.PrintVisual(grid, Title);
}
}
}
}
반응형
'C# 개발 > WPF 관련 서적 예제' 카테고리의 다른 글
Charles Petzold의 WPF Chap. 01 - SayHello 예제 소스 (0) | 2021.09.04 |
---|---|
Charles Petzold의 WPF Chap. 17 - ChooseFont 예제 소스 (0) | 2021.09.03 |
Charles Petzold의 WPF Chap. 17 - PrintBanner 예제 소스 (0) | 2021.09.03 |
Charles Petzold의 WPF Chap. 17 - PrintWithMargins 예제 소스 (0) | 2021.09.02 |
Charles Petzold의 WPF Chap. 17 - PrintEllipse 예제 소스 (0) | 2021.09.02 |