在WindProc VB.NET中捕获WM_SETFOCUS

时间:2014-12-11 14:29:09

标签: vb.net

我有一个继承自基本用户控件类的用户控件。在继承了这个的用户控件上,我放置了一系列文本框。在运行时,我需要知道每个控件何时获得焦点并失去焦点。为此,我在基类中覆盖了WndProc,并尝试捕获那里的消息。我遇到的问题是我从未在消息循环中收到WM_SETFOCUS或WM_KILLFOCUS。

这是WndProc:

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
  Select Case m.Msg
    Case WM_SETFOCUS
      Debug.WriteLine(m.ToString())
    Case WM_KILLFOCUS
      Debug.WriteLine(m.ToString())
    Case Else
      Debug.Print("OTHER: " + m.ToString())
  End Select

  MyBase.WndProc(m)
End Sub

我得到了大量关于获取文本和其他内容的消息,所以我知道我已经到了那里。它永远不会停止在WM_SETFOCUS或WM_KILLFOCUS上。

我做得不好。

1 个答案:

答案 0 :(得分:0)

连接UserControl中所有TextBox的快速示例:

Public Class UserControl1

    Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles Me.Load
        WireTBs(Me)
    End Sub

    Private Sub WireTBs(ByVal cont As Control)
        For Each ctl As Control In cont.Controls
            If TypeOf ctl Is TextBox Then
                Dim TB As TextBox = DirectCast(ctl, TextBox)
                AddHandler TB.GotFocus, AddressOf TB_GotFocus
                AddHandler TB.LostFocus, AddressOf TB_LostFocus
            ElseIf ctl.HasChildren Then
                WireTBs(ctl)
            End If
        Next
    End Sub

    Private Sub TB_GotFocus(sender As Object, e As EventArgs)
        Dim TB As TextBox = DirectCast(sender, TextBox)
        ' ... do something with "TB" ...
        Debug.Print("GotFocus: " & TB.Name)
    End Sub

    Private Sub TB_LostFocus(sender As Object, e As EventArgs)
        Dim TB As TextBox = DirectCast(sender, TextBox)
        ' ... do something with "TB" ...
        Debug.Print("LostFocus: " & TB.Name)
    End Sub

End Class