.net - WPF : Send KeyCode to Active Application

标签 .net wpf

在我的应用程序中,我正在构建一个屏幕键盘,其中各个按键都是 WPF 按钮。我想将相应的虚拟键码(每个按钮)发送到操作系统。

例如,我的应用程序中有一个按钮,内容为“A”。如果我点击它,它应该将虚拟键码“A”发送到操作系统,并且“A”应该添加到事件应用程序的焦点文本框中,就像硬件键盘一样。

我想知道是否有任何类和方法可以用来执行此操作。我尝试使用 SendKeys.SendWait("{A}");但它在 WPF 中不起作用。

最佳答案

阐述我的评论SendKeys.SendWait将与 WPF 一起使用,而 SendKeys.Send将不会。您的问题之一是,如果您尝试将 A 发送到另一个应用程序,则格式错误,大括号表示它是字母 A 不存在的特殊 key 。您需要使用 SendKeys.SendWait("A") 来代替。另一个问题是,如果您将 Wpf 应用程序用作键盘,则在您单击按钮时它是前台应用程序。您将需要深入研究 WinApi 和 Pinvoke 的几个函数,即 FindWindowSetForegroundWindow .

来自 SendKeys.Send 上的链接:

Because there is no managed method to activate another application, you can either use this class within the current application or use native Windows methods, such as FindWindow and SetForegroundWindow, to force focus on other applications.

显示如何切换到另一个应用程序的示例(我使用记事本作为示例)

public partial class MainWindow : Window
{
    [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        SetForegroundWindow(FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad"));
        SendKeys.SendWait("A");
    }
}

关于.net - WPF : Send KeyCode to Active Application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17917447/

相关文章:

C# Entity Framework 属性(有时)为空

c# - WPF - 将可见性绑定(bind)到键的状态

java - Java/.NET 互操作工具(IKVM、JNBridge 等)的效率和有效性

.net - Visual Studio 2010 上的通用处理程序 (.ashx) 智能感知问题

c# - 绑定(bind)到 ViewModel 的集合

c# - 按回车键时在文本框上执行命令

c# - 要使用 AD B2C 验证 .NET Core 3.0 WPF 桌面客户端,如何使用默认操作系统浏览器?

.net - 如何安全访问 DataGridView 列名?

c# - 如何在打开的下拉菜单中填充组合框

wpf - 在混合 wpf/win32 应用程序中定义应用程序范围的热键