получение момента изменения положения курсора X и Y в C # WPF - PullRequest
0 голосов
/ 21 декабря 2011

Я хочу получить момент неизменной позиции курсора. Я имею в виду, когда мышь останавливается, я хочу что-то сделать. Но я буду делать это много раз. Я использовал диспетчерский таймер. Но это не позволяет мне делать то же самое внутри этого. Пример:

        timer.Interval = new TimeSpan(0, 0, 0, 1);
        timer.Tick += (sd, args) => // this is triggered when mouse stops.
        {

            if (a== b)
            {
               I do something here }; // it works until here.

            }


         timer2.Tick += (sd, args ) => // // It doesnt allow me to put this timer here.

         {
               I will do something here when mouse stops.
         }
         };

Ответы [ 3 ]

1 голос
/ 21 декабря 2011

Попробуйте это:

        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 0, 1); /* Try to use larger value suitable for you. */
        timer.Tick += (sd, args) => // This is triggered every 1sec.
        {
            Point currentpoint = /* Define current position of mouse here */ null;
            if (lastpoint == currentpoint)
            {
                /* Do work if mouse stays at same */

                /* { //EDIT*/

                /* I haven't tried this, but it might work */
                /* I'm assuming that you will always do new work when mouse stays */
                DispatcherTimer timer2 = new System.Windows.Threading.DispatcherTimer(
                    TimeSpan.FromSeconds(1), /* Tick interval */
                    System.Windows.Threading.DispatcherPriority.Normal, /* Dispatcher priority */ 
                    (o, a) => /* This is called on every tick */
                    {
                        // Your logic goes here 
                        // Also terminate timer2 after work is done.
                        timer2.Stop();
                        timer2 = null;
                    },
                    Application.Current.Dispatcher /* Current dispatcher to run timer on */
                    );
                timer2.Start(); /* Start Timer */

                /* } //EDIT */

            }
            lastpoint = currentpoint;
        };
        timer.Start();
0 голосов
/ 21 декабря 2011

Красные волнистые линии, говорите вы?

    timer.Interval = new TimeSpan(0, 0, 0, 1);
    timer.Tick += (sd, args) => // this is triggered when mouse stops.
    {

        if (a== b)
        {
           I do something here }; // it works until here.

        }


         timer2.Tick += (sd1, args1 ) => // // It doesnt allow me to put this timer here.
         {
               I will do something here when mouse stops.
         }
     };

Помогает ли это?Я переименовал аргументы, так как вы переопределяете их, и я столкнулся с красными волнистыми линиями в этом случае раньше ...

0 голосов
/ 21 декабря 2011

Вот что вы можете попробовать, чтобы получить положение мыши X и Y после того, как мышь перестала двигаться в течение 1 секунды.Нет необходимости в двойных таймерах и т. Д. Просто зарегистрируйте событие MouseMove для своего окна и сбрасывайте таймер при каждом его перемещении.

    private DispatcherTimer timer;

    public MainWindow()
    {
        InitializeComponent();

        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        var position = Mouse.GetPosition(this);
        // position.X
        // position.Y

        timer.Stop(); // you don't want any more ticking. timer will start again when mouse moves.
    }

    private void Window_MouseMove(object sender, MouseEventArgs e)
    {
        // restart timer. will not cause ticks.
        timer.Stop();
        timer.Start();
    } 
...