如何让 WPF 桌面应用程序捕捉带有文本字符的 Elgato Streamdeck 命令?

How can I get a WPF desktop application to catch a Elgato Streamdeck command with text characters?

我有一个用 NET Core 3.1 编写的 WPF 桌面应用程序,它使用 KeyDown 命令捕获击键。所有字符都被键盘捕获。当我使用 Streamdeck 及其系统文本功能时,它像键盘一样发送键,我的 WPF 应用程序没有捕捉到它。

已在记事本上测试,从 Streamdeck 发送的文本可以正常工作,例如X 1 输入。

当我调试时,唯一发送的是 Enter 键。

private void MyApp_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.X)
    {
        //do something
    }
}

普通键盘一切正常。条形码扫描器也可以。 Streamdeck 不会捕获它发送的文本。

我需要在项目中设置什么才能捕获它吗?

StreamDeck Screenshot

我自己对 Elgato Stream Deck 有点兴趣,所以尝试了 Stream Deck Mobile 应用程序。我发现当应用程序发送文本时,每个字母都会发送一对 WM_KEYDOWNWM_KEYUP windows 消息以及 VK_PACKET virtual-key code 。它建议应用程序利用 SendInput 函数“发送 Unicode 字符,就好像它们是击键一样”。

然后,幸运的是我发现UIElement.PreviewTextInput事件可以捕获每个字母。因此,假设文本以 Enter 键结尾,我们可以通过聚合字母来检索应用发送的文本。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private readonly StringBuilder _buffer = new();

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        if (e.Text is ("\r\n" or "\r" or "\n")) // Key.Return produces a line break.
        {
            if (_buffer.Length > 0)
            {
                OnTextRecieved(_buffer.ToString());
                _buffer.Clear();
            }
        }
        else
        {
            _buffer.Append(e.Text);
        }
        base.OnPreviewTextInput(e);
    }

    protected virtual void OnTextRecieved(string text)
    {
        Debug.WriteLine($"TextRecieved {text}");
    }
}