函数调用仅在包含MessageBox.Show()时有效?

时间:2013-09-02 16:00:34

标签: vb.net

在我目前的项目中,我有一个自制的音响播放器,通过我的musictimer()功能进行操作。下面是一个子命令,当有人点击图片时,命令音频播放器转到下一首歌曲。这非常有效。

Private Sub PictureBox4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox4.Click
    If (ListBox1.Items.Count - 1 > songBeingPlayed) Then
        musictimer("next")
    Else
        musictimer("stop")
    End If
End Sub

下面有一个子命令播放器在歌曲播放结束时命令播放器播放下一首歌曲。这个子程序也可以工作,但只有当我在那里有MessageBox.Show(“blabla”)行时。否则它只是忽略了音乐时间(“下一个”)。显然,整个时间都有弹出消息非常烦人所以我希望它消失了。有谁知道发生了什么?我一无所知。

Private Sub AxWindowsMediaPlayer1_PlayStateChange(ByVal sender As System.Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles AxWindowsMediaPlayer1.PlayStateChange
    If AxWindowsMediaPlayer1.playState = WMPLib.WMPPlayState.wmppsStopped Then
        musictimer("next")
        MessageBox.Show("blabla")
    End If
End Sub

我非常凌乱的音乐家功能。

Function musictimer(ByVal action)
    If action Is "initial" Then
        TextBox1.Text = "0:00"
        Timer1.Stop()
        secondsCounter = 1
        doubledigitsecondCounter = 0
        minuteCounter = 0
    End If

    If action Is "reset" Then
        TextBox1.Text = "0:00"
        Timer1.Stop()
        secondsCounter = 1
        doubledigitsecondCounter = 0
        minuteCounter = 0
        Me.AxWindowsMediaPlayer1.URL = ""
        changePlayButton("play")
    End If

    If action Is "start" Then
        If (ListBox1.Items.Count > 0) Then
            Me.AxWindowsMediaPlayer1.URL = directoryPath + listboxpl(songBeingPlayed)
            AxWindowsMediaPlayer1.Ctlcontrols.play()
            Timer1.Start()
            changePlayButton("pause")
        End If
    End If

    If action Is "pause" Then
        Timer1.Stop()
        AxWindowsMediaPlayer1.Ctlcontrols.pause()
        changePlayButton("play")
    End If

    If action Is "next" Then
        If (ListBox1.Items.Count - 1 > songBeingPlayed) Then
            songBeingPlayed += 1
            musictimer("reset")
            musictimer("start")
            changePlayButton("pause")
        Else
            musictimer("pause")
        End If
    End If

    If action Is "previous" Then
        If (songBeingPlayed > 0) Then
            songBeingPlayed -= 1
            musictimer("reset")
            musictimer("start")
        End If
    End If
End Function

1 个答案:

答案 0 :(得分:5)

PlayStateChanged事件非常臭名昭着。它真的只是为了更新显示状态的UI元素。在该事件中与玩家做任何事情都非常麻烦。对MessagBox的调用可能会产生影响,因为它会为消息循环提供一个消息循环,对ActiveX控件来说总是很重要。

避免麻烦的最佳方法是延迟您的代码,使其在事件被触发后运行并且播放器恢复到静止状态。使用Control.BeginInvoke()方法优雅地完成。像这样:

Private Sub AxWindowsMediaPlayer1_PlayStateChange(ByVal sender As System.Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles AxWindowsMediaPlayer1.PlayStateChange
    If e.newState = WMPLib.WMPPlayState.wmppsStopped Then
        Me.BeginInvoke(New Action(AddressOf NextSong))
    End If
End Sub

Private Sub NextSong()
    musictimer("next")
End Sub