Selfmade OnScreenKeyboard需要第二次点击才能做出反应

问题描述 投票:0回答:1

我有一个TextBox UserControl,它通过单击显示OnScreenKeyboard。启动OnScreenKeyboard的TextBox的CodeBehind如下所示:

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;
        } 

OnScreenKeyboard是一个继承自Window的部分类。 OnScreenKeyboard的构造函数如下所示:

    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();
    }

到目前为止一切正常,除了一件事:OnScreenKeyboard-Window出现后,需要第二次点击才能做出反应。看起来它没有焦点,需要一次点击才能获得焦点。我怎样才能解决这个问题?

我已经在构造函数中尝试了以下内容,但它没有帮助:

this.Focus();
c# wpf xaml
1个回答
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之前,必须加载要聚焦的窗口。

© www.soinside.com 2019 - 2024. All rights reserved.