Welcome

首页 / 软件开发 / .NET编程技术 / Windows 8 键盘上推自定义处理

Windows 8 键盘上推自定义处理2014-07-03在Windows 8 应用程序中,当TextBox控件获得焦点时,输入面板会弹出,如 果TextBox控件处于页面下半部分,则系统会将页面上推是的TextBox不被输入面 板盖住,但是当TextBox是在FlipView控件中时,系统不会将页面上推,所以这种 情况下输入框被输入面板盖住。具体原因不清楚,不知道是不是系统bug。

当输入面板弹出,页面上推的操作可以通过监听InputPane的Showing和Hiding 事件来处理,既然当TextBox在FlipView控件时,系统没有很好的处理页面上推, 那么开发者可以通过监听InputPane的事件来自己处理上推操作。

Windows 8 的一个实例代码Responding to the appearance of the on- screen keyboard sample中介绍了如果监听处理InputPane的相关操作,参考此实 例以FlipView中的TextBox控件为例并对实例代码进行简化处理。

实例中的InputPaneHelper是对InputPane的事件处理的封装,直接拿来使用, InputPaneHelper代码如下:

using System; using System.Collections.Generic; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.Foundation; using Windows.UI.Xaml.Media.Animation;namespace HuiZhang212.Keyboard { public delegate void InputPaneShowingHandler(object sender, InputPaneVisibilityEventArgs e); public delegate void InputPaneHidingHandler(InputPane input, InputPaneVisibilityEventArgs e); public class InputPaneHelper { private Dictionary<UIElement, InputPaneShowingHandler> handlerMap; private UIElement lastFocusedElement = null; private InputPaneHidingHandler hidingHandlerDelegate = null;public InputPaneHelper() { handlerMap = new Dictionary<UIElement, InputPaneShowingHandler>(); }public void SubscribeToKeyboard(bool subscribe) { InputPane input = InputPane.GetForCurrentView(); if (subscribe) { input.Showing += ShowingHandler; input.Hiding += HidingHandler; } else{ input.Showing -= ShowingHandler; input.Hiding -= HidingHandler; } }public void AddShowingHandler(UIElement element, InputPaneShowingHandler handler) { if (handlerMap.ContainsKey(element)) { throw new System.Exception("A handler is already registered!"); } else{ handlerMap.Add(element, handler); element.GotFocus += GotFocusHandler; element.LostFocus += LostFocusHandler; } }private void GotFocusHandler(object sender, RoutedEventArgs e) { lastFocusedElement = (UIElement)sender; }private void LostFocusHandler(object sender, RoutedEventArgs e) { if (lastFocusedElement == (UIElement)sender) { lastFocusedElement = null; } }private void ShowingHandler(InputPane sender, InputPaneVisibilityEventArgs e) { if (lastFocusedElement != null && handlerMap.Count > 0) { handlerMap[lastFocusedElement](lastFocusedElement, e); } lastFocusedElement = null; }private void HidingHandler(InputPane sender, InputPaneVisibilityEventArgs e) { if (hidingHandlerDelegate != null) { hidingHandlerDelegate(sender, e); } lastFocusedElement = null; }public void SetHidingHandler(InputPaneHidingHandler handler) { this.hidingHandlerDelegate = handler; }public void RemoveShowingHandler(UIElement element) { handlerMap.Remove(element); element.GotFocus -= GotFocusHandler; element.LostFocus -= LostFocusHandler; } } }