簡體   English   中英

在vb.net中向文本框輸入隨機字母

[英]Input random letter to textbox in 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'是從不是在其上創建線程的線程訪問的。 任何想法? 謝謝!

之所以收到此異常,是因為您試圖在不是UI線程的線程中更改文本框的文本。

在這種情況下,您可以按照Plutonix的建議在System.Windows.Forms.Timer替換System.Timers.Timer ,這很可能會解決此問題。

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

要在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 InvokeRequired屬性返回True ,則此方法實際上會調用自身。 如果返回False ,則意味着您可以安全地設置Text框的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM