最后,我解决了不使用单行 xaml 代码的情况下无法在全息视图中获取键盘事件的问题,现在我可以在全息视图中显示屏幕触摸键盘,并且可以在我自己的自定义 TextBox 中获取文本输入.我从几天开始就一直在研究它,但我对 UWP API 没有任何想法。我挣扎了很多,在这里和闲暇时问,但没有人能帮助我解决我的问题,但今天我通过使用 xaml 示例代码进行实验得到了解决方案,所以如果有人也面临同样的问题,请按照以下实现
CoreTextEditContext textEditContext =
CoreTextServicesManager.GetForCurrentView().CreateEditContext();
textEditContext.TextUpdating += Context_TextUpdating;
必须实现以下两个事件回调才能在您的 CoreWindow 上获取按键事件,例如 CoreWindow.CharacterReceived、CoreWindow.KeyDown、CoreWindow.KeyUp。我没有收到这些事件,因为我没有实现它们。
textEditContext.TextRequested += Context_TextRequested;
textEditContext.SelectionRequested += Context_SelectionRequested;
在这里你告诉 TextService 你将通过调用 InputPane.TryShow 和 InputPane.TryHide API 来显示和隐藏你自己的键盘。
textEditContext.InputPaneDisplayPolicy = CoreTextInputPaneDisplayPolicy.Manual;
textEditContext.InputScope = CoreTextInputScope.Text;
获取屏幕键盘实例并注册键盘隐藏和显示事件
InputPane OSDKeyboard = InputPane.GetForCurrentView();
OSDKeyboard.Showing += OSDKeyboard_Showing;
OSDKeyboard.Hiding += OSDKeyboard_Hiding;
CoreTextEditContext 事件回调的实现。由于以下功能,CoreWindow 开始工作,否则当我在触摸键盘上按下键时我什么也得不到
private void Context_SelectionRequested(CoreTextEditContext
sender,CoreTextSelectionRequestedEventArgs args)
{
var sel = new CoreTextRange();
sel.StartCaretPosition = 0;
sel.EndCaretPosition = 4;
args.Request.Selection = sel;
}
private void Context_TextRequested(CoreTextEditContext sender,
CoreTextTextRequestedEventArgs args)
{
args.Request.Text = "Holographic_OnScreen_Keyboard";
}
现在您可以通过以下代码行在屏幕键盘上显示。按触摸键盘上的任意键,您将在注册的事件 CoreWindow.CharacterRecieved 和 CoreWindow.KeyDown 回调中获得按下的键代码。从那里您可以在 hololens 2 应用程序中进行文本输入。
textEditContext.NotifyFocusEnter();
OSDKeyboard.TryShow();
https://docs.microsoft.com/en-us/uwp/api/windows.ui.text.core.coretexteditcontext?view=winrt-19041
https://docs.microsoft.com/en-us/uwp/api/windows.ui.viewmanagement.inputpane?view=winrt-19041