Graphics.DrawRectangle在控件事件中不起作用

时间:2014-10-26 19:27:40

标签: vb.net events graphics enter drawrectangle

首先感谢您抽出宝贵的时间来帮助我。

我正在使用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

问题如下:

  • 第一次没有绘制textbox1获得焦点矩形。
  • 第一次没有绘制textbox2获得焦点矩形。

当前两个事件输入被激活时,为什么不绘制矩形?

2 个答案:

答案 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