首页 > 解决方案 > 用户干预我的应用程序时立即触发?

问题描述

我已经一起使用了以下事件,以了解用户是否干预了我的应用程序。

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;
        }
    }
}
}

我不想使用两个代码块,即鼠标事件键盘事件

那么您知道用户干预我的应用程序后立即触发的任何替代代码吗?

标签: c#wpfvb.netwinformsevents

解决方案


您可以使用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());
            }
        }

推荐阅读