I know other users asked this question but I don't know how to solve my problem.
Below there's my code (sorry, maybe it's too long). Visual Studio says "The calling thread cannot access this object because a different thread owns it" on the line sounds[i].Stop();
. Why? And How to solve this problem?
Thank'you so much!
private Thread th = null;
private void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
foreach (PictureBox key in panel.Controls)
{
string name = key.Name;
string[] parts = name.Split('_');
if (e.KeyChar.ToString() == parts[1])
{
th = new Thread(press);
th.Start(new object[] { key, name });
}
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
foreach (PictureBox key in panel.Controls)
{
string name = key.Name;
string[] parts = name.Split('_');
if (Convert.ToChar(e.KeyValue).ToString().ToLower() == parts[1])
leave(key, name);
}
}
private void press(object data)
{
object[] array = (object[])data;
PictureBox pressedKey = (PictureBox)array[0];
string name = (string)array[1];
string[] parts = name.Split('_');
[...] Other code
play(parts[1].ToString());
}
private void leave(object sender, string name)
{
PictureBox pressedKey = sender as PictureBox;
string numero = pressedKey.Name;
string[] parts = numero.Split('_');
[...] Other code
stopPlay(parts[1].ToString());
}
List<System.Windows.Media.MediaPlayer> sounds = new List<System.Windows.Media.MediaPlayer>();
private void play(string note)
{
int i = 0;
string url;
bool diesis = false;
var sound = new System.Windows.Media.MediaPlayer();
while (!diesis && i < (nomi.Length))
{
if (note == nomi[i])
diesis = true;
i++;
};
if (diesis)
{
[...] Other code
}
else
{
url = Application.StartupPath + "\\suoniTastiBianchi\\" + note + ".wav";
sound = new System.Windows.Media.MediaPlayer();
sound.Open(new Uri(url));
sound.Play();
sounds.Add(sound);
}
}
private void stopPlay(string note)
{
for (int i = sounds.Count - 1; i >= 0; i--)
{
sounds[i].Stop();
sounds.RemoveAt(i);
}
}