I am currently working on a Rythm Game for for my course project, and I am having trouble implementing BGM on/off button.
Here is my simplified code:
Form1
public partial class Form1 : Form
{
public SplashScreen()
{
InitializeComponent();
string path= System.Reflection.Assembly.GetEntryAssembly().Location;
axWindowsMediaPlayer1.settings.volume = 0;
axWindowsMediaPlayer1.Ctlcontrols.stop();
axWindowsMediaPlayer1.URL = path.Remove(path.Length - 44) "\\assets\\main.wav";
}
void BGMoff()
{
axWindowsMediaPlayer1.settings.mute = true;
}
void BGMon()
{
axWindowsMediaPlayer1.settings.mute = false;
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 main = new Form2();
main.BGM_off = BGMoff;
main.BGM_on = BGMon;
}
}
Form2
public partial class Form2 : Form
{
public delegate void ClickButton();
public event ClickButton BGM_off;
public event ClickButton BGM_on;
bool BGM = true
public void button4_Click_1(object sender, EventArgs e)
{
if (BGM)
{
button4.BackgroundImage = Properties.Resources.BGMoff;
BGM = false;
BGM_off?.Invoke();
}
else
{
button4.BackgroundImage = Properties.Resources.BGMon;
BGM = true;
BGM_on?.Invoke();
}
}
}
This was made based on comment from this thread by Darin. I believe I followed the steps correctly to get access to axWindowsMediaPlayer
, but I was wrong.
CodePudding user response:
You can easily call the function of another form by creating and saving the second form in a variable and call the function from it.
CodePudding user response:
Looks like your issue is that in this line in Form1_Load
:
Form2 main = new Form2();
main
is created as a local variable.
After you allocate it and register to the events, it goes out of scope.
You can make it a member variable of Form1
instead:
public partial class Form1 : Form
{
// ...
Form2 main;
// ...
}
This way the lifetime of main
will be related to the lifetime of your Form1
.
You code in Form1_Load
should be:
main = new Form2(); // NOTE: this is the member this.main
main.BGM_off = BGMoff;
main.BGM_on = BGMon;
CodePudding user response:
After frustraiting hours of experementation with code i realized my mistake.
It was in a part of code i didnt even include as it was somewhat unrelated to event handling itself.
main.Show(this);
is the culprid. It's code used to open new form, aka switch between menues. I was creating new object form2
of Form2 and going there instead of the one where we signed up for events, therefore events were returning null. and failing to execute functions.