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

WinUI中如何在KeyDown事件里检测Alt键是否按住?

解决WinUI中检测Alt+按键组合的问题

在WinUI里,Alt键对应的虚拟键枚举是VirtualKey.Menu(Windows平台底层将Alt键定义为VK_MENU,因此框架中用Menu来映射)。你可以通过这个枚举值结合InputKeyboardSource.GetKeyStateForCurrentThread方法来检测Alt键是否被按住。

修改后的完整代码如下:

using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Windows.System;

private void AutoSuggestBox_OnKeyDown(object sender, KeyRoutedEventArgs e)
{
    // 检测Alt键是否按住,同时按下方向下键
    bool isAltPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu)
        .HasFlag(CoreVirtualKeyStates.Down);
    
    if (isAltPressed && e.Key == VirtualKey.Down)
    {
        (sender as AutoSuggestBox)?.IsSuggestionListOpen = true;
        // 可选:标记事件已处理,避免后续逻辑干扰
        e.Handled = true;
    }
}

补充说明

  • 若需要区分左Alt和右Alt,可分别使用VirtualKey.LeftMenu和VirtualKey.RightMenu枚举值
  • 确保已引用Microsoft.UI.Input和Windows.System命名空间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:56:02