728x90
728x170

키보드 KeyDown 시 AddHandler  를 이용해 이벤트 처리하는 방법입니다.

AddHandler 에 처리할 Keyboard.PreviewKeyDownEvent 를 명시하고 해당 이벤트 발생시

수행될 메서드(OnKeyHandler)를 연결하면 됩니다.

this.AddHandler(Keyboard.PreviewKeyDownEvent, new KeyEventHandler(OnKeyHandler));

MainWindow.xaml

using System;
using System.Windows;
using System.Windows.Input;

namespace Wpf.AddHandlerTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.AddHandler(Keyboard.PreviewKeyDownEvent, new KeyEventHandler(OnKeyHandler));
        }

        void OnKeyHandler(object sender, KeyEventArgs e)
        {
            messageTextBox.AppendText("key down " + e.Key + Environment.NewLine);
        }
    }
}

MainWindow.xaml.cs

<Window
    x:Class="Wpf.AddHandlerTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:Wpf.AddHandlerTest"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Grid>
        <TextBox x:Name="messageTextBox" />
    </Grid>
</Window>

 

KeyDownEvent 는 내부 컨트롤이 있는 경우 내부 컨트롤에 정의하면 안되면 가장 상위단에 AddHandler 를 통해 등록하여

처리해야 이벤트가 발생되지 않는 현상을 방지할수 있습니다.

결과

728x90
그리드형

'C# > WPF' 카테고리의 다른 글

[C#/WPF] Notifications.Wpf 를 이용한 알림 표시 처리하기  (0) 2023.09.14
[WPF] Parent Binding  (0) 2023.04.20
[WPF] Popup Drag Move 처리하기  (0) 2023.04.19
[WPF] VectorConverter  (0) 2023.04.18
[WPF] Size3DConverter  (0) 2023.04.18
Posted by kjun
,