[英]How To Make A For Loop Wait For User Input?
我有一個for
循環,可以轉到一個站點並發布到其表單。 對於listbox
每個項目,我希望它等待用戶將數據填寫到站點,然后移動。 這里的關鍵是“等待”。
所以我的問題是:是否可以使for
循環等待用戶輸入?
這是我正在工作的for
循環, for
將數據加載到表單中:
if (webBrowser1.DocumentText.Contains("Welcome"))
{
for (int i = 0; i < listBox4.Items.Count; i++ )
{
listBox4.SetSelected(i, true);
listBox5.SetSelected(i, true);
//coded to submit to form
Application.DoEvents();
}
}
這是在網站上單擊提交的代碼:
Application.DoEvents();
foreach (HtmlElement webpageelement in allelements)
{
if (webpageelement.GetAttribute("value") == "Submit")
{
webpageelement.InvokeMember("click");
Application.DoEvents();
}
}
我也嘗試過在沒有代碼的情況下進行for
循環,以使其繼續進行。 例如:i ++並執行if
語句使之繼續運行,但這滯后了我的界面。
進行for
或while
循環以等待用戶輸入不是一個好的解決方案。 不要那樣做 您的程序將在不斷等待條件使之脫離循環的同時不斷工作。 相反,您應該使用事件或其他方法找到解決方案。
如果您不想使用問題注釋中建議的Form.ShowDialog()
解決方案,則可以提出類似的建議:
有一個全局變量,該變量保存我們正在處理的listBox項的索引:
int currentItemIndex;
在“ Submit
按鈕上添加一個Click
事件。 當用戶單擊Submit
,它將調用將處理下一個listBox
項的方法:
private void buttonSubmit_Click(Object sender, EventArgs e) {
// Process next listBox item
ProcessNextItem();
}
處理下一個listBox
項的方法:
private void ProcessNextItem() {
currentItemIndex += 1;
if (currentItemIndex >= listBox.Items.Count) {
// We have gone through all listBox items
// Do nothing
} else {
// Fill predefined information to the website
website.SomeField = listBox.Items[currentItemIndex].SomeField; // Whatever you do to fill predefined information
}
並在開始時調用一個方法(用戶在處理第一個listBox
項之前不會單擊Submit
):
private void Start() {
currentItemIndex = -1;
ProcessNextItem();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.