2015-05-27 21 views
0

我在輸入文本框中的隨機字母時遇到了問題。這裏是代碼:在vb.net輸入隨機字母到文本框

Imports Microsoft.VisualBasic 
Imports System.Timers 

Public Class Form1 
Dim SlovaTimer As Timer 
Dim AbecedaArray() As Char = {"A", "B", "C", "Č", "Ć", "D", "Dž", "Đ", "E", "F", "G", "H" _ 
          , "I", "J", "K", "L", "Lj", "M", "N", "Nj", "O", "P", "R" _ 
          , "S", "Š", "T", "U", "V", "Z", "Ž"} 
Dim counter As Integer = 0 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    SlovaTimer = New Timer(200) 
    AddHandler SlovaTimer.Elapsed, New ElapsedEventHandler(AddressOf Handler) 
    SlovaTimer.Enabled = True 
    Button1.Enabled = False 
End Sub 

Private Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs) 
    If counter = 11 Then 
     SlovaTimer.Stop() 
     Button2.Enabled = False 
    Else 
     Dim ctrl As Control 
     For Each ctrl In Me.Controls 
      If (ctrl.GetType() Is GetType(TextBox)) Then 
       Dim txt As TextBox = CType(ctrl, TextBox) 
       If txt.Tag = counter Then 
        Dim random As New Random 
        Dim randletter As Integer = random.Next(0, 29) 
        Dim letter As String 
        letter = AbecedaArray(randletter) 
        txt.Text = letter 
       End If 
      End If 
     Next 
     SlovaTimer.Start() 
    End If 

這裏的錯誤:跨線程操作無效:從不是創建它的線程以外的線程訪問控制「TextBox1的」。任何想法?謝謝!

+3

使用'System.Windows.Forms.Timer'代替 - 或者從工具箱中拖動一個到表格 – Plutonix

回答

2

由於您試圖更改不是UI線程的線程中的文本框的文本,您會得到此異常。

在這種情況下,您可以用System.Windows.Forms.Timer替代System.Timers.Timer作爲Plutonix在他的評論中提出的建議,這可能會解決問題。

但是,如果將來遇到這些異常,您應該知道如何處理這些異常。

要在winforms中對UI控件進行跨線程調用,您需要使用Invoke。 一個文本框的文本,並委託制定該方法創建一個方法:

Delegate Sub SetTextCallback(txt as TextBox, newString As String) 

Private Sub SetText(txt as TextBox, newString As String) 

    ' Calling from another thread? -> Use delegate 
    If txt.InvokeRequired Then 
     Dim d As New SetTextCallback(AddressOf SetText) 
     ' Execute delegate in the UI thread, pass args as an array 
     Me.Invoke(d, New Object() {txt, newString}) 
    Else ' Same thread, assign string to the textbox 
     txt.Text = newString 
    End If 
End Sub 

現在,你可以看到,這個方法實際上調用本身如果屬性的textbox回報TrueInvokeRequired。如果它返回False,這意味着您可以安全地設置文本框的Text

+0

謝謝。在互聯網上做了一些研究,現在很清楚。謝謝Zohar Peled,你幫了我很多! :) –

+0

如果答案解決了您的問題,您應該接受它,以便其他人會知道問題已解決。 –

相關問題