You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在.NET MAUI中引用System.Windows.Input仍找不到KeyRoutedEventArgs

.NET MAUI Windows平台按键检测解决方案

错误原因分析

你引用的System.Windows.Input是WPF框架的命名空间,而.NET MAUI的Windows平台基于WinUI 3,路由按键事件参数KeyRoutedEventArgs属于Microsoft.UI.Xaml.Input命名空间,因此会出现找不到类型的错误。

修正后的基础按键检测代码

替换正确的命名空间后,普通按键与功能键的检测代码如下:

#if WINDOWS
using Microsoft.UI.Xaml.Input;

public void MyKeyDownEventHandler(object sender, KeyRoutedEventArgs e)
{
    // 检测ESC功能键
    if (e.Key == Windows.System.VirtualKey.Escape)
    {
        // 写入你的业务逻辑
    }
    // 检测普通字母键A
    else if (e.Key == Windows.System.VirtualKey.A)
    {
        // 写入字母A触发的逻辑
    }
}
#endif

组合键检测实现(可选)

如果需要检测组合键,可通过Keyboard.Modifiers判断修饰键状态,示例如下:

#if WINDOWS
using Microsoft.UI.Xaml.Input;

public void MyKeyDownEventHandler(object sender, KeyRoutedEventArgs e)
{
    // 检测Ctrl+C组合键
    if (e.Key == Windows.System.VirtualKey.C 
        && Keyboard.Modifiers == VirtualKeyModifiers.Control)
    {
        // 写入复制操作逻辑
    }
    // 检测Shift+Enter组合键
    else if (e.Key == Windows.System.VirtualKey.Enter 
             && Keyboard.Modifiers == VirtualKeyModifiers.Shift)
    {
        // 写入换行相关逻辑
    }
}
#endif

事件绑定说明

需在Windows平台的页面或控件上绑定KeyDown事件,XAML示例如下(需添加Windows平台条件编译):

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:Windows="clr-namespace:Microsoft.UI.Xaml.Controls;assembly=Microsoft.UI.Xaml"
             x:Class="YourAppNamespace.YourPage">
    <!-- Windows平台专属事件绑定 -->
    <ContentPage.Windows>
        <Windows:Page KeyDown="MyKeyDownEventHandler" />
    </ContentPage.Windows>
</ContentPage>

内容的提问来源于stack exchange,提问作者himbd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 21:48:19