首先感谢您抽出宝贵的时间来帮助我。
我正在使用Form和3个文本框(TextBox1,TextBox2和TextBox3)开发一个项目(Win Application)。
我需要在聚焦时在文本框周围画一个矩形。
代码是:
Private Sub TextBox123_Enter(sender As Object, e As System.EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter
Using g As Graphics = Me.CreateGraphics
Dim r As Rectangle = sender.Bounds
r.Inflate(4, 4)
g.DrawRectangle(Pens.Blue, r)
End Using
End Sub
问题如下:
当前两个事件输入被激活时,为什么不绘制矩形?
答案 0 :(得分:1)
使用CreateGraphics
绘图几乎总是不正确的方法。如果您还注意到,当您从一个盒子移动到另一个盒子时,旧的矩形不会被删除。您需要使用Form_Paint
事件才能使其正常工作。或者......也许更简单的是创建一个比子TextBox大1-2个像素的UserControls并设置UserControl画布的背景颜色,当控件获得焦点时绘制矩形。
表格涂料:
Public Class Form1
Private HotControl As Control
如果您只打算使用TextBoxes,则可以声明它As TextBox
。这样它允许您对其他控件类型执行相同的操作。设置/清除跟踪器:
Private Sub TextBox3_Enter(sender As Object, e As EventArgs) Handles TextBox3.Enter,
TextBox2.Enter, TextBox1.Enter
HotControl = CType(sender, TextBox)
Me.Invalidate()
End Sub
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave,
TextBox2.Leave, TextBox3.Leave
HotControl = Nothing
Me.Invalidate()
End Sub
Me.Invalidate
告诉表单重绘自己,这在Paint:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
If HotControl IsNot Nothing Then
Dim r As Rectangle = HotControl.Bounds
r.Inflate(4, 4)
e.Graphics.DrawRectangle(Pens.Blue, r)
End If
End Sub
您还应该启用Option Strict。
答案 1 :(得分:0)
在click event
处理程序
Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
Using g As Graphics = Me.CreateGraphics()
Dim rectangle As New Rectangle(TextBox1.Location.X - 1, _
TextBox1.Location.Y - 1, _
TextBox1.Size.Width + 1, _
TextBox1.Size.Height + 1)
g.DrawRectangle(Pens.Blue, rectangle)
End Using
End Sub