c# - 用户干预我的应用程序时立即触发?
问题描述
我已经一起使用了以下事件,以了解用户是否干预了我的应用程序。
namespace WpfApplication1
{
public partial class MainWindow : Window
{
static int x, y;
public MainWindow()
{
InitializeComponent();
}
//If User uses the mouse
private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
x = (x + 1);
if ((x == 1))
{
//Do something;
}
}
//If User uses the keyboard
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
y = (y + 1);
if ((y == 1))
{
//Do something;
}
}
}
}
我不想使用两个代码块,即鼠标事件和键盘事件。
那么您知道用户干预我的应用程序后立即触发的任何替代代码吗?
解决方案
您可以使用InputManager.Current.PreProcessInput事件。这通常用于登录注销检查,可以勾选在这种情况下使用。一个简单的示例如下
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
InputManager.Current.PreProcessInput += new PreProcessInputEventHandler(Current_PreProcessInput);
}
private void Current_PreProcessInput(object sender, PreProcessInputEventArgs e)
{
if (e.StagingItem.Input is MouseEventArgs
|| e.StagingItem.Input is KeyboardEventArgs
|| e.StagingItem.Input is TextCompositionEventArgs
)
{
if (e.StagingItem.Input is MouseEventArgs)
{
MouseEventArgs mouseEventArgs = (MouseEventArgs)e.StagingItem.Input;
// no button is pressed and the position is still the same as the application became inactive
if (mouseEventArgs.LeftButton == MouseButtonState.Released &&
mouseEventArgs.RightButton == MouseButtonState.Released &&
mouseEventArgs.MiddleButton == MouseButtonState.Released &&
mouseEventArgs.XButton1 == MouseButtonState.Released )
return;
}
// User activity log for testing
Debug.WriteLine("Got the event :" + e.StagingItem.Input.ToString());
}
}
推荐阅读
- gitlab - 错误:合并失败:合并期间出现问题:3:US-ASCII 中的字节序列无效。请再试一次。在 GitLab 上
- matrix - 在 ThreeJS 中绘制镜像对象
- flutter - 在 Flutter 中将 JSON 作为字符串处理
- apache-flink - Beam WordCount TaskManagerFailure NoClassDefFoundError for MetricUpdates$MetricUpdate
- javascript - Deviantart 的 Greasemonkey/Tempermonkey 脚本
- python - 如何对具有n个元素的数组进行排序,其中k个元素在O(n + k log k)中不合适?
- python - 当日期和时间是整数时,如何使用 Pandas 获取 DateTime 对象?
- data-visualization - 使用 Vegalite 的多直方图
- ios - SwiftUI ScrollView BlendMode 问题
- java - 匹配方法时忽略Accept-Encoding?