「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.18
XML
カテゴリ: C#.NET


以下は、C# WPF アプリケーションでプリンターを呼び出して印刷するサンプルコードです。この例では、PrintDialog を使用して印刷ダイアログを表示し、選択されたプリンターを使用して印刷します。


```csharp

using System;

using System.Printing;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;


namespace PrintExample

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }


        private void PrintButton_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                // 印刷ダイアログを作成

                PrintDialog printDialog = new PrintDialog();


                if (printDialog.ShowDialog() == true)

                {

                    // プリンターが選択された場合


                    // インスタンス化した PrintDocument に PrintVisual メソッドを使って印刷する Visual オブジェクトを渡す

                    printDialog.PrintVisual(contentGrid, "Print Example");

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show($"Error occurred: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            }

        }

    }

}

```


```xml

<Window x:Class="PrintExample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Print Example" Height="200" Width="300">

    <Grid>

        <Button x:Name="printButton" Content="Print" Click="PrintButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center"/>

        <Grid x:Name="contentGrid" Visibility="Collapsed">

            <TextBlock Text="This is the content to print." HorizontalAlignment="Center" VerticalAlignment="Center"/>

        </Grid>

    </Grid>

</Window>

```


この例では、メインウィンドウには印刷ボタンがあり、その下に印刷する内容が含まれるコンテンツグリッドが配置されています。


`PrintButton_Click` イベントハンドラでは、PrintDialog を使用して印刷ダイアログを表示し、選択されたプリンターを使用してコンテンツグリッドを印刷しています。


印刷するコンテンツを変更する場合は、`contentGrid` に適切な UI 要素を追加または変更してください。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.18 08:25:38


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
X
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: