Luiey Ichigo Ответов: 1

Установите конкретное текстовое поле для отображения потока входа в систему


привет,

я создаю приложение для непрерывной отправки информации в облачные сервисы с определенным интервалом. в настоящее время необходимо отправить 10 сведений об устройстве. я использую winform для имитации всех информационных данных для отображения. у меня есть 10 richtextbox, которые обрабатываются как журнал событий для каждого устройства.

имя для каждого richtextbox-rtb_dev001,rtb_dev002 и т. д. Я должен загрузить идентификатор устройства при загрузке формы. При ТИКе таймера я вызову background worker, чтобы запустить ThreadPool и передать объект deviceinformation (ID, State, RTB), где RTB указал, какой richtexbox будет appendtext.

В настоящее время я застрял на объявлении "if deviceid = "dev001", я установлю новый RTB в потоке функций и задам строку "rtb_" & deviceid. Теперь эта часть провалилась.

<pre lang="VB">
    Structure DeviceRecord
        Dim Desc As String
        Dim State As String
        Dim Rtb As RichTextBox
        Sub New(ByVal DevDesc As String, ByVal DevState As String, ByVal rtb As RichTextBox)
            Me.Desc = DevDesc
            Me.State = DevState
            Me.Rtb = rtb
        End Sub
        Sub New(ByVal Files() As DeviceRecord)
            For Each f As DeviceRecord In Files
                Dim fr As New DeviceRecord(f.Desc, f.State, f.Rtb)
            Next
        End Sub
    End Structure
Private Sub datasender_Load(sender As Object, e As EventArgs) Handles MyBase.Load
	bgwWorker1 = New System.ComponentModel.BackgroundWorker
	With bgwWorker1
		.WorkerReportsProgress = True       'we'll need to report progress
		.WorkerSupportsCancellation = True  'allows the user to stop the activity
	End With
	Dim wslist As slaveinformation.Slave() = ws.GetSlaveList()
	If Not (IsNothing(wslist)) Then
		f_tbl = New DataTable
		f_row = f_tbl.NewRow
		For i As Integer = 0 To wslist.Length - 1
			Dim deviceid As String = wslist(i).Name
			Dim state As StateType = wslist(i).State
			Dim name As String = "rtb_" & deviceid.ToString.Replace("-", "").ToLower
			Select Case deviceid
				Case "dev001"
				    slavedevice.Add(New DeviceRecord("dev001", state.ToString),rtb_dev001)
				Case "dev002"
				    slavedevice.Add(New DeviceRecord("dev002", state.ToString),rtb_dev002)
				Case "dev003"
				    slavedevice.Add(New DeviceRecord("dev003", state.ToString),rtb_dev003)
				Case "dev004"
				    slavedevice.Add(New DeviceRecord("dev004", state.ToString),rtb_dev004)
				Case "dev005"
				    slavedevice.Add(New DeviceRecord("dev005", state.ToString),rtb_dev005)
		Next
	End If
	InitializeAzureInstance()
End Sub
Private Sub tmrloop_Tick(sender As Object, e As EventArgs) Handles tmrloop.Tick
	Try
		nowdatetime = DateTime.Now
		tmrloop.Stop()
		tmrloop.Enabled = False
		bgwWorker1.RunWorkerAsync()
		Return
	Catch ex As Exception
		AppendTextBox(rtb_events, "Error timer tick: " & ex.Message.ToString, Color.Red)
	End Try
End Sub
Private Sub StartMyWork()
	Try
		taskstart = DateTime.Now
		For i As Integer = 0 To slavedevice.Count - 1
			devdata(0) = slavedevice.Item(i).Desc
			devdata(1) = slavedevice.Item(i).State
			devdata(2) = slavedevice.Item(i).Rtb
			ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf SubListSelectedSlave), devdata)
			Threading.Thread.Sleep(10)
		Next
	Catch ex As Exception
		AppendTextBox(rtb_events, "Error start my work: " & ex.Message.ToString, Color.Red)
	End Try
End Sub
Private Sub bgwWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgwWorker1.DoWork
	Try
		If bgwWorker1.CancellationPending Then
			e.Cancel = True
			Return
		End If
		ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf StartMyWork))
		Threading.Thread.Sleep(10)
	Catch ex As Exception
		AppendTextBox(rtb_events, "Error backgroundworker do its work: " & ex.Message.ToString, Color.Red)
	End Try
End Sub
Private Sub bgwWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgwWorker1.RunWorkerCompleted
	taskend = DateTime.Now
	Dim duration As TimeSpan = taskend - taskstart
	AppendTextBox(rtb_events, "Task full completed: " & duration.ToString, Color.Blue)
	tmrloop.Enabled = True
	tmrloop.Start()
End Sub
Private Async Sub SubListSelectedSlave(ByVal cname As Object)
	Try
		Dim icnt = 0
		Dim startTime As New DateTime()
		Dim endTime As New DateTime()
		currdate = CInt(Format(nowdatetime, "yyyMMdd"))
		currtime = CInt(Format(nowdatetime, "HHmmss"))
		startTime = DateTime.Now
		
		Dim matches() As Control
		Dim rtb As RichTextBox = New RichTextBox
		matches = Me.Controls.Find(CStr(cname(2)), True)
		If matches.Length > 0 AndAlso TypeOf matches(0) Is RichTextBox Then
			rtb = DirectCast(matches(0), RichTextBox)
		End If

		Dim ctrl As Control
		For Each ctrl In Me.Controls
			If (ctrl.GetType.ToString = "System.Windows.Forms.RichTextBox") Then
				CType(ctrl, RichTextBox).Text = "All textbox text is the same."
			End If
		Next
		
		AppendTextBox(rtb, "Showing data:" & CStr(cname(0), Color.LightGreen)
	Catch ex As Exception
		AppendTextBox(rtb_events, "Error get controller information: " & ex.Message.ToString, Color.Red)
	End Try
End Sub
</pre>


Что я уже пробовал:

Dim matches() As Control
Dim rtb As RichTextBox = New RichTextBox
matches = Me.Controls.Find(CStr(cname(2)), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is RichTextBox Then
	rtb = DirectCast(matches(0), RichTextBox)
End If


Dim ctrl As Control
For Each ctrl In Me.Controls
	If (ctrl.GetType.ToString = "System.Windows.Forms.RichTextBox") Then
		CType(ctrl, RichTextBox).Text = "All textbox text is the same."
	End If
Next

1 Ответов

Рейтинг:
1

User 11061201

Structure DeviceRecord
    Dim Desc As String
    Dim State As String
    Dim Rtb As RichTextBox
    Sub New(ByVal DevDesc As String, ByVal DevState As String, ByVal rtb As RichTextBox)
        Me.Desc = DevDesc
        Me.State = DevState
        Me.Rtb = rtb
    End Sub
    Sub New(ByVal Files() As DeviceRecord) '?
        For Each f As DeviceRecord In Files '?
            Dim fr As New DeviceRecord(f.Desc, f.State, f.Rtb) '?
        Next
    End Sub
End Structure


Какой смысл передавать экземпляр DeviceRecord в DeviceRecord? Вы должны использовать другой подход при создании нескольких экземпляров структуры, вне ее.


If TypeOf(ctrl) Is RichTextBox Then
				DirectCast(ctrl, RichTextBox).Text = "All textbox text is the same."
			End If

'Find RTB
     For Each ctr In Me.Controls
       If (TypeOf(ctr) Is RichtextBox) AndAlso (DirectCast(ctr, RichTextBox).Name.ToLower() = ("rtb_" & deviceID).ToLower()) Then
   slavedevice.Add(New DeviceRecord(deviceID), DirectCast(ctr, RichTextBox))
End If
     Next


Для доступа к элементам управления из другого потока необходимо использовать так называемые делегаты.
В этом примере показано, как изменить свойство Text RichTextBox.

Delegate Sub DEL_AppendText(ByRef rtb As RichTextBox, ByVal txt As String)


Sub Appendext(ByRef rtb As RichTextBox, ByVal txt As String)
    If Me.InvokeRequiered Then
         rtb.Invoke(New DEL_AppendText(AddressOf AppendText), rtb, txt)
    Else
         rtb.AppendText(txt) 'or rtb.Text = txt
    End If
End Sub