0

I make a bot program and i want to send some keyboard keys between some interval of time.

this is the code in my thread. I have recorded: "F" click then wait 4 sec then "S","A","Q" clicks. The problem is that the time (4 sec) is waited and then all the latter's pop up in their order "fsaq"...

public void Run()
    {
        Thread.Sleep(3000);
        for (int i = 0; i <= Form.BotEvents.Items.Count - 1; i++)
        {
            string[] EventText = Form.BotEvents.Items[i].ToString().Split(' ');
            if (EventText[2] == "Time")
            {
                Thread.Sleep(Convert.ToInt32(EventText[3]));
            }
            else
            {
                SendKey(EventText[3]);
            }
            Thread.Sleep(100);
        }
        Run();
    }
TreantBG
  • 1,192
  • 6
  • 25
  • 44

2 Answers2

0

That's because by putting your UI thread asleep, you're preventing the message loop from processing the 'F' key press. You need to run your code on a different thread, or avoid using Thread.Sleep, try System.Windows.FOrms.Timer instead.

Mr. TA
  • 5,230
  • 1
  • 28
  • 35
  • this is a different thread, not the main. but the timer idea is good too :) – TreantBG Jun 12 '12 at 18:54
  • I have a feeling you're mistaking the Thread.Sleep(3000) for your 4s sleep, and your Convert.ToInt32(...) returns the time in seconds, which when passed into Thread.Sleep() is interpreted as milliseconds, hence the illusion of "FASQ" being sent at once... – Mr. TA Jun 12 '12 at 19:01
  • no i'm not mistaken this. and ToInt32 doesn't give me the seconds but the milliseconds – TreantBG Jun 12 '12 at 19:10
0

Another problem with the given code, is that you've got a case of infinite recursion.

public void Foo
{
    for(int i = 1; i < 100; i++)
    {
        if( i % 2 == 0 )
        {
            Console.WriteLine("Foo: " + i);
        }
        else
        {
            Console.WriteLine("Bar: " + i);
        }
    }

    Foo();
}

See the problem here? There's no terminating condition. This bot will run and run and run until it finally runs out of memory (which will happen, since the method is never ending and thus garbage collection is never happening, except within the boundaries of the if and for loops.)

In the short term, it would be a good idea to add an interpreted instruction for some kind of End or Done command, which will return from the calling method. In the long term, considering refactoring to run in an infinite loop with a terminating condition.

Andrew Gray
  • 3,756
  • 3
  • 39
  • 75