我有以下代码,我需要知道按钮的名称,因为该按钮是唯一可以执行任务的按钮。
Class MessageFilter
Implements IMessageFilter
Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
If Form1.SavingData Then
Const WM_KEYDOWN As Integer = &H100
'Const WM_MOUSELEAVE As Integer = &H2A3
Const WM_MOUSE_LEFT_CLICK As Integer = &H201
Select Case m.Msg
Case WM_KEYDOWN, WM_MOUSE_LEFT_CLICK
' Do something to indicate the user is still active.
Form1.SavingData = False
Exit Select
End Select
' Returning true means that this message should stop here,
' we aren't actually filtering messages, so we need to return false.
End If
Return False
End Function
End Class
答案 0 :(得分:2)
我建议您不要使用默认的Form1实例,而是将表单引用作为参数传递给消息过滤器的构造函数。默认表单实例,添加到VB以便于将VB6代码转换为VB.Net。
如果您声明过滤器类如下:
Class MessageFilter
Implements IMessageFilter
Private frm As Form1
Private targetButton As Button
Public Sub New(frm As Form1, targetbutton As Button)
Me.frm = frm
Me.targetButton = targetbutton
End Sub
Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
Const WM_KEYDOWN As Integer = &H100
Const WM_MOUSE_LEFT_CLICK As Integer = &H201
If Me.frm.SavingData AndAlso
m.HWnd = Me.targetButton.Handle AndAlso
(m.Msg = WM_KEYDOWN OrElse m.Msg = WM_MOUSE_LEFT_CLICK) Then
Me.frm.SavingData = False
End If
' Returning true means that this message should stop here,
' we aren't actually filtering messages, so we need to return false.
Return False
End Function
End Class
您可以像这样应用过滤器:
Private filter As MessageFilter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
filter = New MessageFilter(Me, Me.Button2)
Application.AddMessageFilter(filter)
End Sub
这允许您指定要使用的特定按钮。过滤器检查是否要使用其Handle
属性将该消息发送到该特定Button,该属性将是唯一值,而不是使用其Name
属性。