2017-06-07 58 views
1

我有下面的代碼,我需要知道一個按鈕的名稱,因爲該按鈕是唯一啓用了執行任務的按鈕。是否可以在MessageFilter函數中捕獲按鈕名稱?

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

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.fromhandle(v=vs.110).aspx –

回答

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

相關問題