UPDATE:
這是一個有點亂,但一些重構後,它可以幫助你。 我使用預覽事件捕獲文本並強制發送我想要的密鑰;我忽略了預覽處理程序中的所有其他鍵。我確實從KeyDown切換到了KeyUp,讓預覽事件先觸發。我使用_clearNext標誌來跳過/清除關鍵事件。
在XAML
<Window x:Class="EmployeeNavigator.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
PreviewTextInput="Window_PreviewTextInput"
Keyup="Window_KeyUp"
Height="400"
Width="600"
MinWidth="600">
</Window>
代碼隱藏檢測和過程_
private bool _clearNext = false;
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (_clearNext)
{
_clearNext = false;
e.Handled = true;
}
else if (e.Key == Key.OemMinus)
{
e.Handled = true;
}
else if (e.Key == Key.OemQuestion)
{
e.Handled = true;
}
}
private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text.Equals("_"))
{
KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice,
Keyboard.PrimaryDevice.ActiveSource, 0, Key.OemMinus);
args.RoutedEvent = Keyboard.KeyUpEvent;
InputManager.Current.ProcessInput(args);
e.Handled = true;
_clearNext = true;
}
else if (e.Text.Equals("?"))
{
KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice,
Keyboard.PrimaryDevice.ActiveSource, 0, Key.OemQuestion);
args.RoutedEvent = Keyboard.KeyUpEvent;
InputManager.Current.ProcessInput(args);
e.Handled = true;
_clearNext = true;
}
}
我會添加一定有更好的辦法。
的問題是我需要檢測也Esc鍵,返回鍵和Shift鍵,這將無法使用TextInput :( 必須有一種方法來將密鑰轉換爲被鍵入的字符:( – 2010-05-28 07:32:16