Reputation: 1533
Check the code bellow. Its a windows form application. My goal is continue type a random character then press BackSpace then again continue do same non stop. I have written following code but after 1/2 minutes this code not type anything also no error comes. How can i make it in continue non stop loop? Any idea?
private void textBox1_TextChanged(object sender, EventArgs e)
{
SendKeys.Send(RandomString(1));
Thread.Sleep(2000);
SendKeys.Send("{BACKSPACE}");
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
Upvotes: 0
Views: 937
Reputation: 2069
"Non-stop" suggests differently, but IMHO a keys sender should always be able to safely stop before the time period has passed. In the above answer example, the action cannot be stopped by using a "pause" button on the form, because clicking anything on the Windows canvas will put focus and keys will arrive there.
Below is my KeySender class. My version is meant to target only the control that had focus when the key sender was started. Whenever that focus gets lost, the timer is stopped. I introduced a delegate for the key data.
public delegate string KeysProducer();
public class KeySender
{
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
private IntPtr initialFocus = IntPtr.Zero;
private DateTime _startTime = DateTime.Now;
private Timer _timer = null;
private KeysProducer keysProducer = null;
public KeySender(KeysProducer source)
{ keysProducer = source; initialFocus = GetFocus(); }
public KeySender(IntPtr Focussed, KeysProducer source)
{ keysProducer = source; initialFocus = Focussed; }
public bool Sending()
{ return _timer!=null; }
public void StopSendingKeys()
{
if (_timer != null) _timer.Enabled = false;
_timer = null;
}
public void StartSendingKeys(int minutes, int intervalsec)
{
if (_timer == null)
{
_timer = new Timer() { Interval = intervalsec };
_timer.Tick += (s, e) =>
{
if (DateTime.Now - _startTime >= TimeSpan.FromMinutes(minutes))
{ _timer.Enabled = false; _timer = null; }
else
if (initialFocus != GetFocus())
{ _timer.Enabled = false; _timer = null; }
else
if (keysProducer!=null) SendKeys.Send(keysProducer());
};
_timer.Start();
}
}
}
A test:
public class KeySenderDemo
{
private static Random random = new Random();
private KeySender ks;
private bool _deleting = true;
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public string DefaultKeysToSend()
{
return (_deleting = !_deleting) ? "{BACKSPACE}" : RandomString(1);
}
public void Stop()
{
if (ks != null) ks.StopSendingKeys();
ks = null;
}
public KeySenderDemo()
{
Form f = new Form();
TextBox tb = new TextBox();
tb.Parent = f;
tb.Location = new Point(10, 10);
tb.Size = new Size(200, 16);
f.Load += (s, e) =>
{
tb.Focus();
ks = new KeySender(tb.Handle, DefaultKeysToSend);
ks.StartSendingKeys(1, 200);
};
f.Click += (s, e) =>
{
if (ks.Sending()) ks.StopSendingKeys();
else
{
tb.Focus();
ks.StartSendingKeys(1, 200);
}
};
Application.Run(f);
}
}
Click on the form to stop and restart. Call:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
KeySenderDemo ksd = new KeySenderDemo();
//Application.Run(new Form1());
}
}
Upvotes: 1
Reputation: 4258
namespace SendKeys
{
using System;
using System.Linq;
using System.Windows.Forms;
using SendKeys = System.Windows.Forms.SendKeys;
public sealed partial class Form1 : Form
{
private bool _deleting = false;
private DateTime _startTime;
public Form1()
{
InitializeComponent();
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
private void timer2_Tick(object sender, EventArgs e)
{
SendKeys.Send(_deleting ? "{BACKSPACE}" : RandomString(1));
_deleting = !_deleting;
if (DateTime.Now - _startTime >= TimeSpan.FromMinutes(30))
timer2.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
timer2.Interval = 2000;
timer2.Enabled = true;
_startTime = DateTime.Now;
}
}
}
The designer.cs
namespace SendKeys
{
sealed partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.textBox1 = new System.Windows.Forms.TextBox();
this.timer2 = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(26, 30);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(481, 20);
this.textBox1.TabIndex = 0;
//
// timer2
//
this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(530, 292);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Timer timer2;
}
}
Every 2 seconds it ticks. It will alternate between sending the key and deleting the key.
e.g. send a key, 2 seconds passes, delete the key, 2 second passes, send a key...
Updated so that it runs for 30 minutes, then will stop.
Upvotes: 3