我正在制作一个程序,其中我有大约400个文本框,我需要编写一个效果,让它们表明它们有焦点。我可以将视觉部分缩小(除非有人知道如何在VB中的文本框中添加柔和的蓝色轮廓),但是我在创建同时处理所有文本框的GotFocus和LostFocus事件时遇到了麻烦。我试过了
Dim txtBox = Me.Controls.OfType(Of TextBox)
Private Sub TextBox_GotFocus(sender As Object, e As EventArgs) Handles txtBox.GotFocus
但我得到一个“必须有WithEvents变量”错误,我不太明白如何修复。我试过了
Public Sub txtBoxGotFocusHandler(ByVal sender As Object,
ByVal e As System.EventArgs)
For Each txtBox As TextBox In Me.Controls 'References all text boxes in form
If txtBox.Focus = True Then
txtBox.BackColor = Color.Black
End If
Next
我已经尝试了一些我在互联网上看到的其他有些相关的东西,但无济于事。任何帮助将不胜感激
答案 0 :(得分:0)
如果您使用Designer创建了表单,则会自动为您添加WithEvents。
如果您将400个文本框声明为私有字段,则将其声明为Private WitheEvents txtBox As TextBox
如果您以编程方式创建文本框并将其添加到文本框或其他内容的集合中,则无法执行WithEvents。
但所有WithEvents都允许您将Handeles TextBox.SomeEvent
添加到函数中。相反,你可以这样做:
Dim txtBox As New TextBox
...
AddHandler txtBox.GotFocus, AddressOf txtBoxGotFocusHandler
Me.Controls.Add(txtBox)
答案 1 :(得分:0)
您可以使用任何控件在运行时制作应用程序。您可以从SQL查询应用程序的布局,也可以通过简单的更改来更改应用程序布局。
Private FocusRectangle As System.Drawing.Graphics
Private OldRectangle As System.Drawing.Graphics
Private MyTextBoxes As New List(Of TextBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyTextBoxes.Clear()
For xcount = 0 To 399
MyTextBoxes.Add(New TextBox)
With MyTextBoxes.Item(xcount)
.Name = "MyTextBoxes" & (xcount + 1).ToString
.Text = ""
.Location = New Point(0, 0)
.Size = New Size(50, 13)
.Visible = True
AddHandler .GotFocus, AddressOf MyTextBoxes_GotFocus
AddHandler .LostFocus, AddressOf MyTextBoxes_LostFocus
End With
Me.Controls.Add(MyTextBoxes.Item(xcount))
'add them to a panel....
'Panel1.Controls.add(MyTextBoxes.Item(xcount))
Next
End Sub
Sub MyTextBoxes_GotFocus(sender As Object, e As EventArgs)
Dim ThisTextBox As TextBox = DirectCast(sender, TextBox)
Dim xPen As New System.Drawing.Pen(Color.LightBlue)
FocusRectangle = Me.CreateGraphics()
FocusRectangle.DrawRectangle(xPen, ThisTextBox.Location.X - 1, ThisTextBox.Location.Y - 1, ThisTextBox.Size.Width + 1, ThisTextBox.Size.Height + 1)
OldRectangle = FocusRectangle
End Sub
Sub MyTextBoxes_LostFocus(sender As Object, e As EventArgs)
Dim ThisTextBox As TextBox = DirectCast(sender, TextBox)
OldRectangle.Dispose()
End Sub
Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
MyTextBoxes.Item(0).Focus()
End Sub