2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WPFのイベント確認方法

2
Last updated at Posted at 2026-01-10

WPFのイベント可視化テンプレート

WPFで開発していたらこのイベントはどの順番で動くのか分からなくなるときがあります。
特にbehaviorを使っているとき。
そういうときにこのテンプレートを使えばどういう順番でイベントが発生しているかデバッグ出力に出てくるので分かり易いです。
snoopももちろん便利ですが、使いようによっては分かりにくいときがあるので私はこれを使っています。

DebugKeyEventTracer.cs

using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Hogehoge.Debug
{
    internal static class DebugKeyEventTracer
    {
        public static void Attach(FrameworkElement root)
        {
            // PreviewKeyDown(トンネリング)
            root.AddHandler(
                UIElement.PreviewKeyDownEvent,
                new KeyEventHandler(OnPreviewKeyDown),
                handledEventsToo: true);

            // KeyDown(バブリング)
            root.AddHandler(
                UIElement.KeyDownEvent,
                new KeyEventHandler(OnKeyDown),
                handledEventsToo: true);
        }

        private static void OnPreviewKeyDown(object sender, KeyEventArgs e)
            => Dump("Preview", sender, e);

        private static void OnKeyDown(object sender, KeyEventArgs e)
            => Dump("KeyDown", sender, e);

        private static void Dump(string phase, object sender, KeyEventArgs e)
        {
            if (sender is not DependencyObject d)
                return;

            var fe = d as FrameworkElement;

            Debug.WriteLine(
                $"[{phase}] " +
                $"Key={e.Key,-8} " +
                $"Handled={e.Handled,-5} " +
                $"Focus={Keyboard.FocusedElement?.GetType().Name,-20} " +
                $"Sender={fe?.GetType().Name,-20} " +
                $"Name={fe?.Name}"
            );
        }
    }
}

見え方

[Preview] Key=Back     Handled=False Focus=TextBox           Sender=Window               Name=
[Preview] Key=Back     Handled=False Focus=TextBox           Sender=ExplorerPage         Name=
[Preview] Key=Back     Handled=True  Focus=TextBox           Sender=DataGrid             Name=FileListGrid
[KeyDown] Key=Back     Handled=True  Focus=TextBox           Sender=ExplorerPage         Name=

方式A:ファイル単位で #if DEBUG(簡単・確実)

KeyEventTracer.cs をこう包む

#if DEBUG
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;

namespace Hogehoge.DevTools
{
    internal static class KeyEventTracer
    {
        public static void Attach(FrameworkElement root)
        {
            root.AddHandler(UIElement.PreviewKeyDownEvent,
                new KeyEventHandler((s, e) => Dump("Preview", s, e)),
                true);

            root.AddHandler(UIElement.KeyDownEvent,
                new KeyEventHandler((s, e) => Dump("KeyDown", s, e)),
                true);
        }

        private static void Dump(string phase, object sender, KeyEventArgs e)
        {
            Debug.WriteLine($"[{phase}] Key={e.Key} Handled={e.Handled}");
        }
    }
}
#endif

呼び出し側はこれ

#if DEBUG
KeyEventTracer.Attach(this);
#endif

✅ Debug だけで有効
✅ Release では クラス自体が存在しない(生成も参照もなし)

方式B:Conditional 属性(呼び出しだけ無効化)

クラスは残るけど、呼び出しが Release で消えるやつ。

using System.Diagnostics;
using System.Windows;

namespace Hogehoge.DevTools
{
    internal static class KeyEventTracer
    {
        [Conditional("DEBUG")]
        public static void Attach(FrameworkElement root)
        {
            // AddHandler...
        }
    }
}

呼び出し側は #if 不要

KeyEventTracer.Attach(this); // Releaseでは呼び出しが消える

✅ 呼び出しが消える
⚠ AddHandler自体は Attach されないのでOK
✅ 個人的にこれが好き(スッキリ)

実際にはこんな感じ

using Hogehoge.DevTools;

        public MainWindow(
            MainWindowViewModel viewModel,
            INavigationViewPageProvider navigationViewPageProvider,
            INavigationService navigationService,
            WindowSettingsService windowSettingsService
        )
        {
            InitializeComponent();
            DebugKeyEventTracer.Attach(this);
            ...
2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?