想要使用键盘如音乐键盘 - 按键进行播放,松开键以停止播放。应用程序是UWP,目标平台是Windows 10,具有普通的hw键盘。我尝试使用Key_down事件来做到这一点。这是测试代码(XAML页面是空的,所以只有C#代码):
using System;
using System.Diagnostics;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace testKeyborad
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
}
private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
Debug.WriteLine($"CoreWindow_KeyDown: {args.VirtualKey} {args.KeyStatus.WasKeyDown} {DateTime.Now:mm:ss.ss}");
}
}
}
当我拿着钥匙时,事件会反复发射。 args.KeyStatus.WasKeyDown 有一个解决方法,在第一个事件中它是 false (它显示在代码中),但这是一种奇怪的方式。
是否只能获得一个key_down事件?
答案 0 :(得分:0)
根据建议你可以使用一个标志,另外如果按下这个标志你可以按下按键,并使用KeyUp重置它。
private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
if (KeyDown)
{
args.SuppressKeyPress = true;
}
else
{
Debug.WriteLine($"CoreWindow_KeyDown: {args.VirtualKey} {args.KeyStatus.WasKeyDown} {DateTime.Now:mm:ss.ss}");
KeyDown = true;
}
}
public void CoreWindow_KeyUp(CoreWindow sender, KeyEventArgs args)
{
KeyDown = false;
}
答案 1 :(得分:0)
当我使用XNA和Monogame时,要走的方法是存储按下的最后一个键并与按下的新键进行比较。我相信同样的行为也适用于您的项目。但我不知道这是否最适合您的问题
public sealed partial class MainPage : Page
{
private Key _lastKeyPressed;
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
}
private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
if(e.Key != _lastKeyPressed)
{
//do something
Debug.WriteLine($"CoreWindow_KeyDown: {args.VirtualKey} {args.KeyStatus.WasKeyDown} {DateTime.Now:mm:ss.ss}");
}
_lastKeyPressed = e.Key;
}
}