컨트롤들은 기본적으로 Tab 키를 누르면 다음 컨트롤로 Focus가 이동하게 되어 있습니다.

 

Tab키가 아닌 Enter키 혹은 지정한 키로 이동하고 싶다면 아래의 코드와 같이 진행하면 되겠습니다.

 

 

 

    public static class FocusAdvancement
    {
        public static bool GetAdvancesByEnterKey(DependencyObject obj)
        {
            return (bool)obj.GetValue(AdvancesByEnterKeyProperty);
        }
        public static void SetAdvancesByEnterKey(DependencyObject obj, bool value)
        {
            obj.SetValue(AdvancesByEnterKeyProperty, value);
        }
        public static readonly DependencyProperty AdvancesByEnterKeyProperty =
            DependencyProperty.RegisterAttached("AdvancesByEnterKey", typeof(bool), typeof(FocusAdvancement),
            new UIPropertyMetadata(OnAdvancesByEnterKeyPropertyChanged));
        static void OnAdvancesByEnterKeyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as UIElement;
            if (element == null) 
                return;
            if ((bool)e.NewValue) 
                element.KeyDown += Keydown;
            else 
                element.KeyDown -= Keydown;
        }
        static void Keydown(object sender, KeyEventArgs e)
        {
            if (!e.Key.Equals(Key.Enter)) 
                return;
            var element = sender as UIElement;
            if (element != null) 
                element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

}

 

 

FocusAdvancement Class는 static Class입니다.

 

AdvancesByEnterKey 라는 이름의 의존프로퍼티를 등록하였습니다.

 

값이 True 일때에는 KeyDown 이벤트를 등록하고, False 일때에는 KeyDown 이벤트를 해제합니다.

 

KeyDown이 발생하였을 때, 누른키가 Enter 키라면 다음 포커스로 이동합니다.

 

 

Xaml에서는 아래와 같이 FocusAdvancement static Class의 AdvancesByEnterKey의 값을 True로 설정해주시면

 

Enter키가 입력되었을 때 다음 컨트롤로 포커스가 이동하게 됩니다.

 

 

 <TextBox ct:FocusAdvancement.AdvancesByEnterKey="True"/> 

 

 

 

예를들어 가상키보드를 구현할 때 가상키보드에 포커스가 옮겨지면 안됩니다.

 

Win32의 SetWindowLong 함수를 사용하시면 포커스가 이동되지 않는 Window를 생성하실 수 있습니다.

 

 

 

private const int GWL_EXSTYLE = -20;

        private const int WS_EX_NOACTIVATE = 0x08000000;

 

        [DllImport("user32.dll")]

        public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

 

        [DllImport("user32.dll")]

        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

 

        protected override void OnSourceInitialized(EventArgs e)

        {

            base.OnSourceInitialized(e);

 

            WindowInteropHelper helper = new WindowInteropHelper(this);

            IntPtr ip = SetWindowLong(helper.Handle, GWL_EXSTYLE,

                GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE);

        } 

 

 

 

 

 

 

'.Net > WPF' 카테고리의 다른 글

WPF Xaml에서 특수문자 사용  (0) 2013.07.11
WPF 기존 Style에 Style 추가  (0) 2013.07.11
WPF WndProc  (0) 2013.07.10
Binding.UpdateSourceTrigger  (0) 2013.07.09
[MVVM Galasoft.MvvmLight.WPF4] EventToCommand, 이벤트 정보를 넘기자!  (0) 2013.07.05

+ Recent posts