Search code examples
c#wpfuser-controlskeydown

How to leave WPF UserControl somewhere inside UserControl?


I'm making a UC (UserControl) in WPF. I have some text boxes in the UC. I want to leave the UC when the user pressed "Return key" on one of them. I want return key to treating like Tab key in the main window. How can I implement it?


Solution

  • I found this post in my searches and it was the answer to my problem.

    The idea is to have a class named SendKeys* and use its method in key down event of the control.

    public static class SendKeys
      {
        /// <summary>
        ///   Sends the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        public static void Send(Key key)
        {
          if (Keyboard.PrimaryDevice != null)
          {
            if (Keyboard.PrimaryDevice.ActiveSource != null)
            {
              var e1 = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key) {RoutedEvent = Keyboard.KeyDownEvent};
              InputManager.Current.ProcessInput(e1);
            }
          }
        }
      }
    

    Then use it like this:

    private void textBoxesKeyDown(object sender, KeyEventArgs e) {
                switch (e.Key)
                {
                    case Key.Return:
                        SendKeys.Send(Key.Tab);
                        break;
                }
     }
    

    *Note: SendKeys is a class in WinForm that is not present in WPF. By the way you can implement using these codes.