为了其他人的利益,我的黑客代码。
我的应用程序正在等待读卡器刷卡。以下内容存在于监视刷卡的对象的构造函数中(这是一个附加项目;大多数注释光标都被编辑掉了):
// this is where we handle the space and other keys wpf f*s up.
System.Windows.Input.InputManager.Current.PreNotifyInput +=
new NotifyInputEventHandler(PreNotifyInput);
// This is where we handle all the rest of the keys
TextCompositionManager.AddPreviewTextInputStartHandler(
Application.Current.MainWindow,
PreviewTextInputHandler);
两种方法:
/// <summary>
/// Handles the PreNotifyInput event of the input manager.
/// </summary>
/// <remarks>Because some controls steal away space (and other) characters,
/// we need to intercept the space and record it when capturing.</remarks>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The
/// <see cref="System.Windows.Input.NotifyInputEventArgs"/>
/// instance containing the event data.</param>
private void PreNotifyInput(object sender, NotifyInputEventArgs e)
{
// I'm only interested in key down events
if (e.StagingItem.Input.RoutedEvent != Keyboard.KeyDownEvent)
return;
var args = e.StagingItem.Input as KeyEventArgs;
// I only care about the space key being pressed
// you might have to check for other characters
if (args == null || args.Key != Key.Space)
return;
// stop event processing here
args.Handled = true;
// this is my internal method for handling a keystroke
HanleKeystroke(" ");
}
/// <summary>
/// This method passes the event to the HandleKeystroke event and turns
/// off tunneling depending on whether or not Capturing is true.
/// Also calls StopCapturing when appropriate.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The
/// <see cref="System.Windows.Input.TextCompositionEventArgs"/>
/// instance containing the event data.</param>
private void PreviewTextInputHandler(object sender,
TextCompositionEventArgs e)
{
HanleKeystroke(e.Text);
}
当有人按下一个键(或向系统发送一个击键)时,会触发PrenotifyInput事件。在这种情况下,我决定它是否是一把特殊的钥匙(对我来说,我必须担心空间,但其他钥匙显然需要特别注意)。如果它是一个特殊的键,我将“处理”该事件,停止对该击键的所有进一步处理。然后我调用在空间中传递的内部处理方法(或者我刚刚截获的任何特殊键)。
所有其他键都由previewtextinputhandler方法处理。
这段代码中有很多东西被去掉了。确定刷卡事件发生的时间、确定刷卡完成的时间、安全措施(如果我从未停止捕获刷卡,则超时)等都将被删除。您如何做这些事情将取决于您的代码需求。