2010-04-20 117 views
0

我的模塊中有一個功能,用戶可以通過 掃描系統中的串行端口數,並且當用戶點擊「自動掃描」按鈕時,代碼將不得不離開 通過每個串口發送一條測試消息並等待 的回覆。使用Winforms更新進度條c#

我正在使用進度條控件來顯示自動掃描的過程。 爲此,我需要將值代碼中的「x」和「Y」值更新爲 。我怎樣才能通過價值,因爲我的代碼已經在獲得serialports的foreach循環中已經是 。

Y =應通過串行端口 X =應通過每個端口迭代的總數的值和傳遞值

希望我與REQ清楚。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     string strAckData = ""; 

     foreach (SerialPort sp in comPortsList) 
     { 
      sp.Open(); 
      string sendData = "Auto scan"; 
      sp.Write(sendData); 
      strAckData += "Connection live on port " + sp.ReadExisting() + "\n"; 
      sp.Close(); 

      double dIndex = (double)x; **//How to pass the value here ?** 
      double dTotal = (double)y; **//How to pass the value here ?** 
      double dProgressPercentage = (dIndex/dTotal); 
      int iProgressPercentage = (int)(dProgressPercentage * 100); 

      // update the progress bar 
      backgroundWorker1.ReportProgress(iProgressPercentage); 

     } 
     richTextBox1.Invoke(new MethodInvoker(delegate { richTextBox1.Text = strAckData; })); 
    } 

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     ProgressBar.Value = e.ProgressPercentage; 
    } 

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 
     StatusLabel.Text = "Auto Scan completed"; 
    } 

回答

1

您可以從您的comPortsList變量中獲得端口數。那麼指數只是一個遞增循環變量的事:

double dTotal = (double)(comPortsList.Count); 
double dIndex = 0; 

foreach (SerialPort sp in comPortsList) 
{ 
    // talk to serial port as at the moment 

    dIndex = dIndex + 1; // or ++dIndex to be more concise 
    double dProgressPercentage = dIndex/dTotal; 
    // etc. 
} 
+0

@itowlson,更清晰..Ÿ應該可用端口和X的總數值應該是被打開的端口值那時候。在這種情況下,X不是一個常數值。每次執行代碼時,X的值都會發生變化sp.open() – Anuya 2010-04-20 02:55:30

+0

我已更新我的答案以反映此情況。很抱歉對於這個誤會。我仍然不確定我是否完全理解了港口「價值」的含義 - 儘管如此,如果我仍然不在意的話,我會表示歉意。 – itowlson 2010-04-20 04:11:27