gpt4 book ai didi

c# - 是否可以在应用程序级别连接到硬件键盘事件?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:15:40 25 4
gpt4 key购买 nike

我正在为 iOSAndroidUWP 开发一个 Xamarin.Forms 应用程序。

我想在应用程序级别(而不是单个页面级别(因为它是 Xamarin.Forms 应用程序))挂接硬件键盘事件,以便当用户按下键盘上的键时,我可以在我的申请。

在 Android 上,我使用 MainActivity 上的以下事件完成此操作:。

public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
//process key press
return base.OnKeyUp(keyCode, e);
}

是否有适用于 Xamarin iOS 的等效项?

最佳答案

您可以使用 KeyCommands跟踪硬件键盘的按键。

keyCommands

A responder object that supports hardware keyboard commands can redefine this property and use it to return an array of UIKeyCommand objects that it supports. Each key command object represents the keyboard sequence to recognize and the action method of the responder to call in response.

The key commands you return from this method are applied to the entire responder chain. When an key combination is pressed that matches a key command object, UIKit walks the responder chain looking for an object that implements the corresponding action method. It calls that method on the first object it finds and then stops processing the event.

在 Xamarin.forms 中,您必须在 iOS 平台上为 ContentPage 创建自定义渲染器。然后可以在该页面呈现器中添加键盘命令。

如果您希望按键操作可以由 ViewController(Page) 处理,而不仅仅是输入控件(例如 Entry),请使用 canBecomeFirstResponder 使 viewcontroller 成为第一响应者。

比如iOS平台ContentPage的自定义渲染器可能是这样的:

using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using KeyCommandsInXamarinForms.iOS;

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]
namespace KeyCommandsInXamarinForms.iOS
{
public class MyCustomPageRenderer : PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);

if (e.OldElement != null || Element == null)
{
return;
}

//Create your keycommand as you need.
UIKeyCommand keyCommand1 = UIKeyCommand.Create(new NSString("1"), UIKeyModifierFlags.Command, new ObjCRuntime.Selector("Action:"));
UIKeyCommand keyCommand2 = UIKeyCommand.Create(new NSString("\t"), 0, new ObjCRuntime.Selector("Action:"));
//Add your keycommands
this.AddKeyCommand(keyCommand1);
this.AddKeyCommand(keyCommand2);
}

[Export("Action:")]
private void Excute(UIKeyCommand keyCommand)
{
Console.WriteLine(String.Format("key pressed - {0}", keyCommand.Value);
}


//Enable viewcontroller to become the first responder, so it is able to respond to the key commands.
public override bool CanBecomeFirstResponder
{
get
{
return true;
}
}
}
}

注意这一行,使用 typeof(ContentPage) 作为处理程序参数,那么您不需要更改 PCL 中的任何内容:

[程序集:ExportRenderer(typeof(ContentPage), typeof(MyCustomPageRenderer))]

关于c# - 是否可以在应用程序级别连接到硬件键盘事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com