0

首先感谢您在百忙之中抽出时间来帮助我。

我正在开发一个带有表单和 3 个文本框(TextBox1、TextBox2 和 TextBox3)的项目(Win 应用程序)。

聚焦时,我需要在文本框周围绘制一个矩形。

代码是:

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

问题如下:

  • textbox1 第一次获得焦点矩形时未绘制。
  • textbox2 第一次获得焦点矩形时未绘制。

为什么在触发前两个事件时不绘制矩形?

4

2 回答 2

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。

于 2014-10-26T21:07:49.970 回答
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
于 2014-10-26T20:04:31.180 回答