Question

Sometimes, If I hold down for example the left arrow key, the pictureBox will stop drawing the coordinates of my character. A prime example is the yellow dot encircled in red. By holding down the left arrow key, the pictureBox did not constantly draw my characters location, until I hit another key/let go of the arrow key, then the picturebox started updating again (as you can see encircled in purple).

Also, another error I am experiencing is the fact that it should only be drawing one yellow dot and one 'blue whirlpool' per location; while it is drawing multiple (as you can see).

The code below is what I am using to replicate the picture results.

private Thread grabValues;

private Bitmap bm;

private Image image1;
private Image image2;

private Graphics gM;

void RGraphics()
{
    image1 = Properties.Resources.image1;
    image2 = Properties.Resources.image2;
}

void RInvokeMe()
{
    while (true)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new UpdateControlsDelegate(MUpdate));
            this.Invoke(new UpdateControlsDelegate(CUpdate));
        }
        else
        {
            MUpdate();
            CUpdate();
        }
    }
}

void MUpdate()
{
  pictureBox1.ImageLocation = "http://urlexample/r/we.png";
}

void CUpdate()
{
        bm = new Bitmap(pictureBox1.Image);

        gM = Graphics.FromImage(bm);

        gM.CompositingMode = CompositingMode.SourceOver;

        MDraw.DrawBlueDot(gM, image2, X2, Y2);
        MDraw.DrawYellowDot(gM, image1, X1, Y1);

        pictureBox1.Image = bm;
        pictureBox1.Refresh();
}

public Form2()
{
    InitializeComponent();

    RGraphics();

    grabValues = new Thread(new ThreadStart(RInvokeMe));
    grabValues.IsBackground = true;
    grabValues.Start();
}
Was it helpful?

Solution

Basically you start a thread (grabValues, implemented by function RInvokeMe) which endlessly invoke on your form methods MUpdate and CUpdate. When you invoke a method then you post a message on the windows message queue in order to let the window execute the given function. But when you press a key even the keypress message is posted to the windows queue... but maybe it is not served quickly because of the tons of invoke requests you are already executing on the form.

You could try to introduce a small delay (Thread.Sleep(500);) in your RInvokeMe loop just to see if the problem is there...

Then if so, I would consider to completely re-design your project in order to avoid such a scenario (if your characters are only moved only when pressing keys, why you simply do not redraw the scene only upon keypress but you do it continuously?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top