【问题标题】:event form.shown works but form.load doesn't事件 form.shown 有效,但 form.load 无效
【发布时间】:2013-07-07 21:52:10
【问题描述】:

我正在使用 Visual Basic 2010,我正在为我正在构建的程序编写 c 代码,我的问题是我设置了 Media.SoundPlayer,我希望它在表单加载时激活所以我的代码看起来像这样(编辑:此代码不起作用,在调试中加载时声音不会播放,我没有收到错误)

Private Sub BGMusic(ByVal x As Integer)
        Dim msp As New Media.SoundPlayer
        Dim Music As String = Install + "\Music\innmusic.wav"
        msp.SoundLocation = Music
        If x = 1 Then
            msp.Play()
        Else
            msp.Stop()
        End If
    End Sub

Private Sub Innmenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            BGMusic(1)
    End Sub

我还想指出 Install + "\Music\innmusic.wav" 是一个有效的路径,因为我可以设置一个按钮来运行 BGMusic(1) 并播放音乐。就我的目的而言,form.shown 会起作用,但我想知道我未来的程序出了什么问题,以便我可以使用 form.load

【问题讨论】:

  • + 不是 VB 中的字符串连接运算符。 & 是。
  • @Dan-o + 和 VB.net 中的 & 都适用于字符串连接。
  • 我会尝试调试一个镜头,相同的代码适用于不同的表单页面,但在某些页面上似乎无法执行
  • 注意:如果你有 Option Strict On,你应该只使用+ 来连接字符串。

标签: vb.net winforms visual-studio-2010


【解决方案1】:

您的Install 变量有可能是空的或未正确初始化,而您没有显示它的声明位置。下面我给你一个例子:

Public Class Innmenu

Dim Install As String = ""

Private Sub Innmenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    BGMusic(1) ' It will not play because Install is still empty
End Sub

Private Sub BGMusic(ByVal x As Integer)
    Dim msp As New Media.SoundPlayer
    Dim Music As String = Install + "\Music\innmusic.wav"
    msp.SoundLocation = Music
    If x = 1 Then
        msp.Play()
    Else
        msp.Stop()
    End If
End Sub


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Install = "C:\" 'Let us assume that your folder Music and file innmusic.wav is in C:
BGMusic(1) ' Music will now play because Install has now the right value assigned

End Sub

顺便为你的BGMusic尝试做Try Catch的方法如:

Private Sub BGMusic(ByVal x As Integer)
    Dim msp As New Media.SoundPlayer
    Dim Music As String = Install + "\Music\innmusic.wav"
    msp.SoundLocation = Music

    Try
       If x = 1 Then
        msp.Play()
       Else
        msp.Stop()
       End If

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

End Sub

如果有任何错误,您将得到反馈。

【讨论】:

  • 我知道安装变量不是空的,因为就像我在我的问题中所说的那样,一个按钮确实激活了 BGMusic(1) 但我觉得我错过了一些启动顺序,因为在我的一些表单上代码有效,而其他代码无效,我复制并粘贴了代码
  • 您确定您的 Install 变量具有正确的值吗?您是否尝试过调试/跟踪它?顺便说一句,你在这个上使用了线程吗?因为如果它有可能在某个地方发生变化。
猜你喜欢
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
相关资源
最近更新 更多