SendKeys.Send继续非停止循环

时间:2018-08-17 10:34:53

标签: c#

检查下面的代码。它是Windows窗体应用程序。我的目标是继续键入一个随机字符,然后按BackSpace,然后再次继续做同样的不停操作。我已经编写了以下代码,但1/2分钟后,此代码未键入任何内容,也没有错误出现。我如何在继续不停循环中做到这一点? 任何想法?

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());
}

2 个答案:

答案 0 :(得分:3)

    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;
        }
    }
}

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;
    }
}

每2秒滴答一声。它将在发送密钥和删除密钥之间交替。

例如发送一个密钥,2秒钟过去,删除密钥,2秒钟通过,发送一个密钥...

已更新,因此可以运行30分钟,然后将停止。

答案 1 :(得分:1)

“不间断”的建议有所不同,但是恕我直言,密钥发送者应该始终能够在该时间段过去之前安全地停止。在上面的答案示例中,无法通过使用表单上的“暂停”按钮来停止操作,因为单击Windows画布上的任何内容都将使焦点对准并且键将到达那里。

下面是我的KeySender类。我的版本只针对启动密钥发送者时具有焦点的控件。每当失去焦点时,计时器就会停止。我为关键数据引入了代表。

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();
        }
    } 
 }

测试:

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);
    }
   }

单击表格以停止并重新启动。致电:

static class Program
{
 [STAThread]
 static void Main()
 {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    KeySenderDemo ksd = new KeySenderDemo();
    //Application.Run(new Form1());
 }
}