LoginSignup
1
0

More than 1 year has passed since last update.

[C#]WPFでマルバツ表示(自動で消えるWindow)

Posted at

この記事は

WPFアプリケーションにおいて、ユーザーのアクションに対して良い/悪いをおおげさに表現したい場合がある

たとえば・・・

  • 検査アプリケーションで良品と不良品を表示したい
  • マウスではない非接触の入力デバイスからの入力があった際に、受け付けたことをユーザーにフィードバックしたい
  • 会社内でマルバツゲームをつくる業務が降ってきた場合

ゴール

  • Goodボタンを押すと緑の丸印が浮かぶ
  • Badボタンを押すと赤のバツ印が浮かぶ

Animation1.gif

動画には収めていないが
親ウィンドウのセンターに表示されるので、ウィンドウが移動しても追従する

ソースコード

要点だけ載せる

XAML

  • 初期表示位置は、すでにあるウィンドウの中央にする(WindowStartLocation
  • WindowStyleNoneにすることで、上部のバーを消す
Green.xaml
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Width="200"
    Height="200"
    Background="Green"
    WindowStartupLocation="CenterOwner"
    WindowStyle="None">
    <Grid>
        <Label
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Content="〇"
            FontSize="128"
            Foreground="White" />
    </Grid>
</Window>

C#(コードビハインド)

ContentRenderedイベントに「2秒後に自身をクローズする」処理を追加する
LoadedActivatedイベントでは画面が真っ白のまま、中身が描画されずに閉じてしまう

using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Markup;

namespace PopUp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click1(object sender, RoutedEventArgs e) =>
            Button_ClickCore("../../GreenWindow.xaml");

        private void Button_Click2(object sender, RoutedEventArgs e) =>
            Button_ClickCore("../../RedWindow.xaml");

        private void Button_ClickCore(string path)
        {
            Window w = null;
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                w = (Window)XamlReader.Load(fs);
            }
            w.Owner = this;

            w.ContentRendered += (ss, ee) =>
            {
                Thread.Sleep(2000);
                w.Close();
            };

            w.ShowDialog();
        }
    }
}

糸冬了!!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0