是否可以在VB.Net(2008)中处理mouseDown事件,无论控制是否触发mouseDown事件?基本上,我只想在“表单级别”捕获mouseDown事件,并且不希望在每个控件中编写mouseDown事件处理程序。有没有办法做到这一点?
答案 0 :(得分:4)
这是非常不寻常的,你几乎总是真的关心点击了什么特定控件。并且有一个MouseDown事件,它根据单击的控件执行特定操作。但是你可以在输入事件发送到控件本身之前捕获输入事件。您需要使用IMessageFilter接口。最好用代码示例解释:
Public Class Form1
Implements IMessageFilter
Public Sub New()
InitializeComponent()
Application.AddMessageFilter(Me)
End Sub
Protected Overrides Sub OnFormClosed(ByVal e As System.Windows.Forms.FormClosedEventArgs)
Application.RemoveMessageFilter(Me)
End Sub
Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
REM catch WM_LBUTTONDOWN
If m.Msg = &H201 Then
Dim pos As New Point(m.LParam.ToInt32())
Dim ctl As Control = Control.FromHandle(m.HWnd)
If ctl IsNot Nothing Then
REM do something...
End If
REM next line is optional
Return False
End If
End Function
End Class
请注意,此过滤器对您应用中的所有表单都有效。如果要使其仅针对一个表单,则需要对ctl值进行过滤。
答案 1 :(得分:1)
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'note - this will NOT work for containers i.e. tabcontrols, etc
For Each c In Me.Controls
Try
AddHandler DirectCast(c, Control).MouseDown, AddressOf Global_MouseDown
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
Next
End Sub
Private Sub Global_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs)
Debug.WriteLine(DirectCast(sender, Control).Name)
End Sub