2014-04-28 62 views
0

我有兩個按鈕「開始」按鈕和「停止」按鈕。我通過單擊開始按鈕來運行程序。我想在啓動按鈕期間停止程序。但該計劃將不會迴應,直到開始buttun完成工作。在開始的時候我該如何檢查stop stoptun。我聽說過線程,但我不知道我該怎麼做。按鈕單擊另一個內部的事件

Private Sub Button_Start (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    //my code 
    //check always if the user push stop if no continue if yes go to this sub 
    //my code 
end sub 

Private Sub Button_Stop (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 
    stopClick = True 
    Dim Response As Integer 
    Response = MessageBox.Show("Do you really want to exit?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 
    If Response = vbYes Then 
    Me.Close() 
    End If 
End Sub 
+0

您需要四個空格才能在此站點縮進您的代碼塊。嘗試命名你的控件。 Button1是否啓動? Button3是否停止? – LarsTech

+0

yes按鈕1是開始,按鈕3是停止 – user3556795

+0

@ user3556795充分尊重:爲什麼您聲明'響應'爲[Integer](http://msdn.microsoft.com/zh-cn/library/06bkb8w2.aspx) ,爲其分配一個[DialogResult](http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult(v = vs.110).aspx),並將其與[MsgBoxResult]( http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.msgboxresult(v=vs.110).aspx)? –

回答

0

你可以在一個函數中使用線程放Button1的代碼,並使用線程。
你可以參考這個例子

'Thread created to handle the Background process for start_function 
Dim t As System.Threading.Thread 

Private Sub start_function() 
    While True 
     'your code here for Eg: 
     Dim i As Integer 
     i = i + 1 
    End While 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    t = New System.Threading.Thread(AddressOf Me.start_function) 
    t.Start() 

End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    t.Abort() 
End Sub 
+0

其實我在這個領域是新的,我不知道如何使用它:( – user3556795

+0

對不起,我得到了這個錯誤,我怎麼能解決它跨線程操作無效:控制'Chart1'從一個線程以外的線程訪問它創建於。 – user3556795

0

拖動一個BackgroundWorker組件到您的形式。

Imports System.ComponentModel 

Public Class Form1 

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click 
    Me.Text = "Busy Doing Work" 

    BackgroundWorker1.WorkerSupportsCancellation = True 
    BackgroundWorker1.RunWorkerAsync() 
End Sub 

Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click 
    Me.Text = "Asking to Cancel" 
    BackgroundWorker1.CancelAsync() 
End Sub 

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
    While Not BackgroundWorker1.CancellationPending 
     System.Threading.Thread.Sleep(1000) 
    End While 
End Sub 


Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 
    Me.Text = "Cancelled" 
End Sub 

End Class 
相關問題