Search code examples
c#winformsmutewmplib

Starting music in Form 1 and stopping in Form 2


I'm looking to make a 'Music on/off' button in my application. I'm using the following code in Form 1, this is the form in which I play the music:

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

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

        public Form1()
        {
            InitializeComponent();
        }   


        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                wplayer.URL = "music/main.mp3";
                wplayer.controls.play();
            }
            catch { }    

        }

I want the music to stop when I press a button in Form 2, I've tried the following code, but it doesn't seem to work:

Form1 frm1 = new Form1();
frm1.wplayer.controls.stop();

(This code is used in the button click event.)

This is a Windows Forms application. I'm using the WMPLib. Any help would be much appreciated, thanks.


Solution

  • Use

    public static WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    

    then call it from Form2 with

    Form1.wplayer.controls.stop();
    

    Currently you are just instantiating new instance of Form1 in your Form2 which will have different wplayer instance than the one you have started the music.