0

I am using code to repeatedly teleport a button to random places every 0.5 seconds, but when I try to click it, it doesn't work.

I've tried using code to refresh the button which solved the visual bugs, but it is still not clickable. I've been using Thread.Sleep(500);.

    int repeat = 100000;
    for (int i = 0; i < repeat; i++)
    {
        int x = 50;

        int y = 50;
        x += 10; 

        y += 10;

        button1.Location = new Point(x, y);

        Random rand = new Random();
        x = rand.Next(ClientSize.Width);  

        y = rand.Next(ClientSize.Height);

        button1.Location = new Point(x, y);
        Thread.Sleep(500);
        button1.Refresh();
    }
Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
  • Use the Button.Click event. Insert the random generation code alone (no loops). Move `Random rand = new Random();` outside the event handler. Then, `int x = rand.Next(ClientSize.Width - button1.Width); int y = rand.Next(ClientSize.Height - button1.Height); button1.Location = new Point(x, y);`. Remove `Thread(...)` an `Refresh()`. – Jimi Oct 26 '19 at 05:46
  • this works, but i need a code to repeat it and also delay it each time, im going for a game that when you click a button, another button keeps on teleporting around and you have to try and click it before it teleports away. – AverageROBLOXian Oct 26 '19 at 06:00
  • You can use a [System.Windows.Forms.Timer](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.timer) (this Timer, not the other Timers). Enable the Timer when a user clicks the first button, disable it in the second (jumping) Button's `Click` event if the user can catch it in the `Timer.Interval` span (before the `Timer.Tick` event raises). Decrease/modify the `Timer.Interval` as needed. – Jimi Oct 26 '19 at 06:09
  • im new to c# so i dont really understandd much but I will keep trying, thank you. – AverageROBLOXian Oct 26 '19 at 06:17
  • 1
    Well, that Timer is a Component you can also find in the ToolBox. Drop it on a Form an configure it in the Properties panel. Enable it in the first Button.Click, disable it in the second's, if the user can get it, or in the `Timer.Tick` event itself if the user cannot get the jumping button in time. – Jimi Oct 26 '19 at 06:23
  • thanks, i got it figured out – AverageROBLOXian Oct 26 '19 at 23:10

1 Answers1

0

your problem is with Thread.Sleep ..it blocks your UI thread.

consider using System.Windows.Forms.Timer instead ...

review L.B answer here:

https://stackoverflow.com/a/12039732/10573560

OMR
  • 11,736
  • 5
  • 20
  • 35