vb.net - 是否可以在 MessageFilter 函数中捕获按钮名称?

标签 vb.net

我有以下代码,我需要知道按钮的名称,因为该按钮是唯一能够执行任务的按钮。

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

最佳答案

我建议您不要使用默认的 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 属性而不是使用其 Name 属性将消息发送到该特定 Button,该属性将是唯一值。

关于vb.net - 是否可以在 MessageFilter 函数中捕获按钮名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415644/

相关文章:

vb.net - 使用 XmlWriter 在 XML 中写入行

vb.net - 更改图像不透明度时遇到问题

vb.net - 使用用户名(vb.net)从事件目录中获取名字和姓氏

wpf - 在设计时绑定(bind)到 WPF 标签、按钮等?

c# - 如何编写多行 RegEx 表达式

c# - 什么是NullReferenceException,如何解决?

VB.net Graphics.DrawString 与 DirectionRightToLeft 混合了我的字符串

vb.net - 使用线程打开表单

vb.net - 检查2个数据库是否存在

vb.net - 如何在使用 Visual Studio 2010 创建的 Excel 加载项中执行 .Onkey 事件?