0

我刚刚从 C++ 和 Rad Studio “迁移”到 C# 和 Visual Studio,因为我可以在 Internet 上看到更多的教程和 VC 帮助。但是..我有一个问题。

我知道在创建表单时(程序启动时)如何播放音乐。但是我怎样才能停止使用正常播放音乐TButton

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _01_21_2019
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            // play an intro sound when a form is shown
              WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
              wplayer.URL = "intro.mp3";
              wplayer.controls.play();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            wplayer.controls.stop(); // Here it is not working - "current context"



        }
    }
}

编译器说

错误 CS0103 当前上下文中不存在名称“wplayer””

我试图移动wplayer.controls.stop()play(); 它有效。但是如何使用按钮停止音乐呢?

这是pastebin上的代码:

https://pastebin.com/v9wDn5mJ

4

1 回答 1

2

您应该在函数之外实例化对象,以便它可用于类实例。

您可能还想研究 mvvm 模式。在编写 WPF 和其他一些应用程序时非常有帮助。

public partial class Form1 : Form
{
    WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        // play an intro sound when a form is shown    
        wplayer.URL = "intro.mp3";
        wplayer.controls.play();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        wplayer.controls.stop();
    }
}
于 2019-01-21T13:19:04.337 回答