2017-10-15 98 views
-3

我想创建一个从多行文本框向外部程序发送密钥的程序。 在文本框中是多行文本,但我需要第一行, 并将它发送到外部程序。C#如何在带有sendkeys的循环中读取第一行,然后是第二行,然后是第三行?

这个想法是,在一个循环中完成它,并在它到达最后一行时停止。

我做了一些代码,但它并不像我需要的那样工作,即时通讯不是最好的这种编程语言。

文本在多行文本框:

Hello im here 
Here to create 
Create for honor 
honor for all 
all for hello 
Hello im here 
Here to create 
Create for honor 
honor for all 
all for hello 

代码:

private void button1_Click(object sender, EventArgs e) 
    { 
     // Countdown of 5 seconds before the SendKeys starts sending. 
     timer1.Start(); 
     System.Threading.Thread.Sleep(5000); 
      for (int i = 0; i < richTextBox1.Lines.Length; i++) 
     { 
      SendKeys.Send(richTextBox1.Lines[i] + "\r\n"); 
      // First line 
      // Start timer1 agian to read second line. 
      // 
     } 
     // Loop ends when it hits the last line (Bottom). 
} 

什么在下面的代码发生不正是我需要的, 它将分隔行一次发送整个文本.. 这样的:

Hello im here 

Here to create 

Create for honor 

honor for all 

all for hello 

Hello im here 

Here to create 

Create for honor 

honor for all 

all for hello 

但我需要像这样:

Hello im here 
//first line -> Timer1 ends -> Start Timer1 agian to read second line 
Here to create 
//Second line -> Timer1 ends -> Start Timer1 agian to read third line 
Create for honor 
//Third line -> Timer1 ends -> Start Timer1 agian to read fourth line 

等等等到循环点击最后一行,并停在最后一行。

回答

2

您的计时器实际上没有做任何事情,因为你正在使用Thread.Sleep睡觉,而不是等待计时器事件 - 让你在开始5秒睡一次,然后永远不再。在移动到下一行之前

for (int i = 0; i < richTextBox1.Lines.Length; i++) 
{ 
    System.Threading.Thread.Sleep(5000); 
    SendKeys.Send(richTextBox1.Lines[i] + "\r\n"); 
} 

这样一来,每一次你都会睡5S迭代:

只需更改您的代码。

如果您的示例中显示了多条换行符,请检查Lines字符串是否已经包含终止换行符(在这种情况下,您将使每个字符串以两个换行符结尾)。


这可能是值得铭记,除非这是在UI线程(不推荐)上发生的情况,用户可以愉快地你这样做时编辑文本框中的文本。你应该做一些UI的东西来阻止它,或者在功能开始时只需要克隆一个Lines成员,然后使用该副本。

+0

Got it!但如何只获得第一条线? 我得到了您的代码,并将richTextBox1.Lines [i]更改为richTextBox1.Lines [0],因此它只会选取第一行。 它发送第一行! :d 但也有117行的文本框,并将其发送117X的第一行.. 如何挑选只在第一行没有第一线去乘 –

+0

@AlJuicebox你只想要发送的第一线?这不是你最初提出的问题。在这种情况下,只需删除'for'循环并执行'Thread.Sleep',然后执行'SendKeys.Send(richTextBox1.Lines [0] +“\ r \ n”);'。 – hnefatl

+0

我得到了它的工作。对不起,我没有问起第一个地方.. 我做了for(int i = 0; i

相关问题