Reputation: 11
So, i've been trying to use SendKey.Send method with a for loop, and for some reason it gets stuck in an infinite loop only when i use it there. I've tried the code without it, and it worked for some reason.
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < trackBar2.Value; i++)
{
SendKeys.Send("{ENTER}");
System.Threading.Thread.Sleep(trackBar1.Value);
}
}
What seems to be the problem?
*EDIT: It can't be the "Enter" key because it does the same thing with other keys and strings, for example:
SendKey.Send("a");
Upvotes: 0
Views: 760
Reputation: 1010
Can you try running your SendKeys.Send("{ENTER}");
in a background thread. I am not sure why it is blocking your main thread but the following approach is working.
static void Main()
{
// setup some form state
Form form = new Form();
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
// start the worker when the form loads
form.Load += delegate
{
worker.RunWorkerAsync();
};
worker.DoWork += delegate
{
// this code happens on a background thread, so doesn't
// block the UI while running - but shouldn't talk
// directly to any controls
for (int i = 0; i < 500; i++)
{
worker.ReportProgress(0, "Item " + i);
Thread.Sleep(150);
}
};
worker.ProgressChanged += delegate(object sender,
ProgressChangedEventArgs args)
{
SendKeys.Send("{Enter}");
};
Application.Run(form);
}
After five hundred iterations my application responded back.
Upvotes: 0
Reputation: 5477
You press button1, at which time the code shown will be executed. This then sends Enter to button1 (because this still has focus), causing that code to run again, etc.
Thus, you have created a loop.
If you try with a different key sent, for instance a
, then the program will hang for a bit, due to the Thread.Sleep
, but after that should become responsive again.
Upvotes: 3