0

I was trying to do async loop on keydown, to move image as long as button is pressed.

    private async void Window_KeyDown(object sender, KeyEventArgs e)
    {
        await Task.Run(() =>
        {
            while (e.IsDown)
            {
                if (e.Key.ToString() == "D")
                    Width.Text = (int.Parse(Width.Text) - 10).ToString();
            }

        });
    }

But it cousing an error: InvalidOperationException, and mscorlib.pdb not loaded.

0

2 Answers 2

2

Add a bool to your form ( bool isDDown = false )

on the keydown event set isDDown = true; on the keyup event set isDDown = false;

add a timer to your form and check however often you need to, update if true.

It wont be quite as continuous as this one is, but it should get rid of your error

Sign up to request clarification or add additional context in comments.

Comments

0

Pretty simple way, and perhaps overly complex way to do it. Spawn a thread with a while loop which continuously adds to your GUI thread's dispatch the task you want to do continuously. It does this aslong you are holding down the mouse button, when you let go, it stops adding jobs to do, and any jobs queued will fail because of a check before it actually does any work

bool isGoing = false;

private void MouseMouseDown(object sender, MouseButtonEventArgs e)
{
    isGoing = true;
    new Thread(new ThreadStart(() => { while (isGoing) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { if (isGoing)
    {
        //Whatever you want to happen continuously ie. move your image
    }}));}})).Start();
}

private void MouseUp(object sender, MouseButtonEventArgs e)
{
    isGoing = false;
}

This will get rid of your error, and be continuous.

Note:

I did this with mouse presses, but it will work exactly the same with keypresses

The speed of your image moving will depend on how good the computer is, I recommend either, using a timer, or even better, use delta time calculations when moving the image. that way you can move the image X/per second, but keep the position updating every possible chance, which results in the smoothest and most consistent motion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.