简体   繁体   中英

SendKeys.Send(“hello”); continuously sending string how can i send only once

This code is continuously sending a string. I need a solution which can send the supplied string only once by clicking a button in the window which has the focus.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SendKeys.Send("This is a test...");
    }
}

The issue seems to be the fact that the button1 control has the focus, and when you send certain keys to it (like the space in your example), it triggers the Click event, and you end up in an infinite loop.

Try adding a TextBox to your form and then set focus to that first (or if you already know the thing that should receive the text, ensure that it has the focus before you call SendKeys ):

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Focus();
    SendKeys.Send("This is a test...");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM