2017-10-15 54 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

相關問題