Selfmade OnScreenKeyboard needs second tap to react

时间:2017-12-18 08:09:30

标签: c# wpf xaml

I have a TextBox UserControl which shows a OnScreenKeyboard by clicking it. The CodeBehind of my TextBox which starts the OnScreenKeyboard looks like this:

X

The OnScreenKeyboard is a partial class which inherits from Window. The Constructor of the OnScreenKeyboard looks like this:

private void TextBoxText_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox textbox = sender as TextBox;
            US_Keyboard keyboardWindow = new US_Keyboard(textbox, Window.GetWindow(this));
            if (keyboardWindow.ShowDialog() == true)
                textbox.Text = keyboardWindow.InputSource.Text;
        } 

So far everything works fine, except one thing: After the OnScreenKeyboard-Window shows up, it needs a second tap to react. It looks like it has no focus and needs one click to get the focus. How can i fix this?

I already tried the following in the constructor, but it does not help:

    public US_Keyboard(TextBox owner, Window wndOwner)
    {
        InitializeComponent();
        this.Owner = wndOwner;
        this.DataContext = this;

        //Delete text in textbox
        if (InputSource.Text.Length > 0)
        {
            OldTextBoxValue = InputSource.Text;
            InputSource.Text = "";
        }

        //Set caret to start point of textbox
        AdornerLayer layer = AdornerLayer.GetAdornerLayer(owner);
        CaretAdorner adorner = new CaretAdorner(owner);
        adorner.OffsetX = _CaretOffsetXDefault;
        layer.Add(adorner);
        _adorner = adorner;
        _layer = layer;

        SetKeyboardSize();
        SetKeyboardPosition();
    }

1 个答案:

答案 0 :(得分:0)

您可以考虑使用Win32 API:

using System;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace YourSolution
{
    static class WindowExtensions
    {
        [DllImport("User32.dll")]
        internal static extern bool SetForegroundWindow(IntPtr hWnd);

        public static void SetFocus(this Window window)
        {
            var handle = new WindowInteropHelper(window).Handle;
            SetForegroundWindow(handle);
        }
    }
}

如果要关注窗口,请使用window.SetFocus(); 注意:在调用SetFocus之前,必须先加载要聚焦的窗口。