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 が最初にフォーカスを得たとき、四角形は描画されません。

最初の 2 つのイベントが発生したときに長方形が描画されないのはなぜですか?

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、フォーム自体を再描画するように指示します。これは、ペイントで発生します。

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 に答える