2013-12-04 4 views
0

У меня есть несколько кнопок в панели 1 и в зависимости от продолжительности (количества тиков) между событием MouseDown и MouseUp изображение отображается в панели2. Нажатая кнопка определяет местоположение изображения. Программа работает нормально, когда каждая кнопка нажата в первый раз. Проблема возникает, когда вторая кнопка нажата, потому что изображение не изменится. Например. нажата кнопка 1, подсчитывается 4 тика и отображается pic A ..... button1 снова нажата, отсчитывается 7 тиков, а pic B отображается вместо pic A, но проблема в том, что pic A остается там! Я думаю, что это что-то делать с помощью метода OnPaint, но после нескольких попыток я не смог решить эту проблему, любое предложение приветствуются ... TksИзображение фона фона не обновляется

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing; 

namespace SimplePiano 
{ 
    class MusKey : Panel 
    { 
      protected int duration; 
      public int musicNote; 
      public TextBox txt1 = new TextBox(); //To test if musicNote refers to the correct pitch integer. 
      public TextBox txt2 = new TextBox(); //To test the number of ticks. 
      protected Timer timer = new Timer(); 

      public MusKey(int iNote, int x, int y): base() 
      { 
       musicNote = iNote; 
       this.Location = new Point(x, y); 
       this.Size = new Size(50, 200); 
       this.BackColor = Color.White; 
       this.BorderStyle = BorderStyle.FixedSingle; 
       this.Visible = true; 

       this.MouseDown += new MouseEventHandler(this.MusKey_MouseDown); 
       this.MouseUp += new MouseEventHandler(this.MusKey_MouseUp); 
      } 

      protected void MusKey_MouseDown(object sender, EventArgs e) 
      { 
       duration = 0; 
       timer.Interval = 100; 
       timer.Tick += new EventHandler(timer1_Tick); 
       txt1.Text = Convert.ToString(musicNote)+" down"; //To test if musicNote refers to the correct pitch integer. 
       timer.Tick += new EventHandler(timer1_Tick); 
       timer.Enabled = true; 
       timer.Start(); 
       duration = 0; 
      } 

      protected void MusKey_MouseUp(object sender, EventArgs e) 
      { 
       timer.Stop(); 
       txt1.Text = Convert.ToString(musicNote)+ " up"; //To test if musicNote refers to the correct pitch integer. 
       txt2.Text = Convert.ToString(duration);   //To test the number of ticks. 
       timer.Enabled = false; 
       string bNoteShape = ""; 

       if (duration < 5) bNoteShape = "Crotchet.png"; 
       if (duration > 5) bNoteShape = "minim.png"; 
       MusicNote musNote = new MusicNote(this.musicNote, bNoteShape); 

       Form1.Ms.Controls.Add(musNote); 

      } 

      private void timer1_Tick(object sender, EventArgs e) 
      { 
       duration++; 
      } 
    } 
} 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing; 

namespace SimplePiano 
{ 
    public class MusicNote: PictureBox 
    { 
     public string path = ""; 
     public int pitch; //The no. of the music key (e.g. the sound freuency). 
     public string noteShape; //Mapped to a note shape(e.g. Crotchet, Minim, Quaver etc.) 
     public int noteDuration; 

     public MusicNote(int iPitch, string iNoteShape):base() 
     { 
      pitch = iPitch; 
      noteShape = iNoteShape; 
      Location = new Point((pitch*40)-40, 100); 
      Size = new Size(40, 40); 
      //Bitmap bmp = new Bitmap(noteShape + ".png"); 
      BackgroundImage = Image.FromFile(noteShape); 
      this.BackColor = Color.Transparent; 
      Image = Image; 
      this.Visible = true; 
      this.BringToFront(); 
     } 

     protected override void OnPaint(PaintEventArgs pe) 
     { 
      base.OnPaint(pe); 
     } 
    } 
} 
+1

Что такое 'MusicNote'? некоторый тип управления Picture Box? это основная проблема, и мы не можем помочь, не видя ее. –

+0

Да MusicNote - это объект, который наследуется от PictureBox. Я добавил класс MusicNote на вопрос – user2307236

ответ

1

Чтобы быть честным, это предположение, но, надеюсь, вы получить пару указателей:

MusicNote musNote = null; 
protected void MusKey_MouseUp(object sender, EventArgs e) 
{ 
    timer.Stop(); 
    txt1.Text = Convert.ToString(musicNote)+ " up"; //To test if musicNote refers to the correct pitch integer. 
    txt2.Text = Convert.ToString(duration);   //To test the number of ticks. 
    timer.Enabled = false; 
    string bNoteShape = ""; 

    if (duration < 5) bNoteShape = "Crotchet.png"; 
    if (duration > 5) bNoteShape = "minim.png"; 

    //Remove the previous musNote Picture box before adding another one: 
    if (musNote != null) Form1.Ms.Controls.Remove(musNote); 
    musNote = new MusicNote(this.musicNote, bNoteShape); 

    Form1.Ms.Controls.Add(musNote); 

    //maybe a red herring, but just encase make sure picture box is on top: 
    musNote.BringToFront() 
} 

Я не понимаю, почему вы назначаете изображение на изображение?

public MusicNote(int iPitch, string iNoteShape):base() 
{ 
    pitch = iPitch; 
    noteShape = iNoteShape; 
    Location = new Point((pitch*40)-40, 100); 
    Size = new Size(40, 40); 
    //Bitmap bmp = new Bitmap(noteShape + ".png"); 
    BackgroundImage = Image.FromFile(noteShape); 
    this.BackColor = Color.Transparent; 
    Image = Image; //<- why assign Image to Image? 
    this.Visible = true; 
    this.BringToFront(); // <- try this line in the MusKey class instead, again red herring 
} 
+0

. Это ошибка, это должно быть изображение img ...... Я попробую, так как сейчас я на работе и обновляю вас что случилось .. Tks .. – user2307236

+0

Да, Джереми это отлично работает ... я только переместил this.BringToFront(); к MusKey и отлично работал. Я не удалял изображение с изображением MusicNote. Надеюсь, это не вызовет у меня проблемы при покупке MusicNotes в коллекции, так что я буду воспроизводить все заметки непрерывно. Но я имею в виду хранить их в словаре ..... Tks – user2307236

Смежные вопросы