2013-04-23 88 views
0

我有一個我在VB 2010中開發的應用程序。它由一系列Windows窗體和一個偵聽器進程組成,它監聽來自MIDI設備(鍵盤等等)。此偵聽器進程在單獨的線程中運行。如何從遠程線程觸發WinForms按鈕點擊

使用回調函數和調用方法我可以使用MIDI設備上演奏的音符的值(代碼如下)更新其中一個窗體上的文本框的值。

我似乎無法做到的是觸發按鈕之一按鈕,以便一段代碼使用另一個回調函數在同一窗體上運行並調用。

我搜索了一下,找不到任何工作示例,所以我不確定這是否可行 - 我希望這是因爲這是我項目的最後1%!

下面是更新窗體上的文本框的工作,我需要修改什麼才能點擊名爲btn_NextSection的同一窗體上的按鈕?

' Because the MIDI listener process runs in a different thread 
' it can read the states of controls on the parent form but it 
' cannot modify them so we need to identify the parent process 
' and update the text box as that one instead 

' Set up the callback 
Private Delegate Sub SetNextSectionTextCallback(ByVal [text] As String) 

' Updates NextSection 
Private Sub SetNextSectionText(ByVal [text] As String) 
    ' Function to see if the thread that tries to update the 
    ' text box is the same as the one that started it. If it 
    ' isn't then locate parent process and update as that one 
    If callerInstance.txt_NextSection.InvokeRequired Then 
     Dim d As New SetNextSectionTextCallback(AddressOf SetNextSectionText) 
     callerInstance.Invoke(d, New Object() {[text]}) 
    Else 
     callerInstance.txt_NextSection.Text = [text] 
    End If 
End Sub 

在此先感謝!

+0

所以你想模擬被點擊的按鈕的外觀(視覺效果?),或者你想觸發在click事件中運行的代碼。 – PatFromCanada 2013-04-23 15:22:32

回答

0

假設您想要運行代碼,而不是模擬按鈕點擊,請嘗試這樣的事情。 Invoke需要一個函數,因此您可能需要創建一個虛擬返回對象。

Private Sub btn_NextSection_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btn_NextSection.Click 
    NextSection() 
End Sub 

Private Function NextSection() As Object 
    'do something on the UI thread 
    Return Nothing ' to satisfy the requirements of Invoke 
End Function 

Private Sub AnotherThreadHere() 
    'call NextSection on the UI thread 
    Application.Current.Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Background, New Action(Function() NextSection())) 
End Sub 
+0

感謝您的回覆帕特,你說得對,我想運行位於另一種形式的代碼。我試過你的建議,但有兩個問題。首先,我沒有System.Windows.RoutedEventArgs - 我有System.Windows.Forms,但沒有RoutedEventArgs選項。其次,我沒有訪問Application.Current.Dispatcher – user1647208 2013-04-23 16:13:12

+0

對不起,我沒有意識到它是WPF特定的。我還沒有在winforms中工作過一段時間。看來Invoke畢竟是正確的想法。 – PatFromCanada 2013-04-23 16:27:20

+0

哈哈!沒問題,謝謝你的幫助。 – user1647208 2013-04-23 16:54:56