Iterating through an array and play notes - c#

I have an array which is populated by MusicNotes. Each MusicNote is an object with it's properties, e.g. pitch and duration. Duration is created using a timer in the MusicNote class.
The problem is that when I iterate through the array and play all the sounds the duration of each MusicNote is lost and it will play the whole wav file (for each note).
I know that the problem is related to the timer and I know that it maybe related to the Play() method in the MusicNote but I don't have any ideas on how to fix it. I have posted my the code related to this problem.
public class MusicNote : PictureBox
{
Timer tmr1 = new Timer();
int tmr1duration;
public SoundPlayer sp = new SoundPlayer();
public Timer tmr = new Timer();
public int pitch; //The no. of the music key (e.g. the sound freuency).
public int noteDuration; //Shape of note.
public string noteShape;
static int xLoc = 0;
int yLoc = 100;
public MusicNote(int iPitch, int iNoteDuration)
: base()
{
pitch = iPitch;
noteDuration = iNoteDuration;
Size = new Size(40, 40);
this.BackColor = Color.Transparent;
this.MouseClick += new MouseEventHandler(MusicNote_MouseClick);
this.MouseDown += new MouseEventHandler(MusicNote_MouseDown);
this.MouseUp += new MouseEventHandler(MusicNote_MouseUp);
tmr1.Tick += new EventHandler(tmr1_Tick);
tmr.Tick += new EventHandler(ClockTick);
}
public void ShowNote()
{
if (this.noteDuration == 1) noteShape = "Quaver.png";
if (this.noteDuration == 4) noteShape = "Crotchet.png";
if (this.noteDuration == 7) noteShape = "minim.png";
if (this.noteDuration == 10) noteShape = "DotMin.png";
if (this.noteDuration == 12) noteShape = "SemiBreve.png";
this.BackgroundImage = Image.FromFile(noteShape);
this.BackColor = Color.Transparent;
Location = new Point(xLoc, yLoc);
xLoc = xLoc + 40;
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
public void Play()
{
sp.SoundLocation = this.pitch + ".wav";
sp.Play();
//Timer to play the duration
this.tmr.Interval = 100 * this.noteDuration;
this.tmr.Start();
}
void ClockTick(object sender, EventArgs e)
{
sp.Stop();
tmr.Stop();
}
private void MusicNote_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Play();
}
}
}
}
And this is the class were I have the array...
public class MusicStaff: Panel
{
public ArrayList musicNotes = new ArrayList(); //Array to store the Music Notes.
SoundPlayer sp = new SoundPlayer();
public void AddNote(MusicNote newNote) //Method to add the notes.
{
musicNotes.Add(newNote);
}
public int ListSize()
{
return musicNotes.Count; //Returns the size of the list.
}
public void PlayAll()
{
foreach (MusicNote m in musicNotes)
{
m.Play();
}
I have removed some code from the classes which is not replated to the problem so that question is not too long. Any help how can I solve this would be greatly appreciated. Tks.

Try something like this:
public void PlayAll()
{
foreach (MusicNote m in musicNotes)
{
m.sp.Stop();
m.sp.PlaySync();
Thread.Sleep(m.noteDuration); //duration should be in milliseconds
}
}
Should this work you can remove your timer completely.
I suggest you look into the use of Properties in C# to not let fields be public.
By the way I did this assignment two years ago :)

Related

How to make Form Visible in C#

I am trying to design a piano for an assignment in C#. I have created a MusicKey class which stores music keys (as well as a BlackMusicKey class). I am populating the panel, 'panel1' with music keys like this:
this.panel1.Controls.Add(bmk);
In the music key constructor, I am setting a location and size for each music key, as well as ensuring that Visibility is set to true. However, when I run the form, it is completely blank.
Is there something that I am missing? I am quite sure that there is nothing wrong with the visibility of the music keys, so surely there is something that I am missing with regards to making the panel visible.
Any help will be appreciated, thanks!
Note: I have also tried using panel1.Show() which still did not work.
All relevant code can be found down below:
MusicKeyClass:
class MusKey : System.Windows.Forms.Button
{
private int musicNote; //determines the pitch mapped to number
public MusKey(int iNote, int x, int y) : base()
{
musicNote = iNote;
this.Location = new System.Drawing.Point(x, y);
this.Size = new System.Drawing.Size(20, 80);
this.Visible = true;
}
public int getMusicNote()
{
return musicNote;
}
}
Form1 Class:
public partial class Form1 : Form
{
int count = 0;
int xLoc = 50;
int yLoc = 30;
int[] whitePitch = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24 };
Panel panel1 = new Panel();
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
Button button1 = new Button();
private void Form1_Load(object sender, EventArgs e)
{
this.Paint += new PaintEventHandler(function);
MusKey mk;
BlackMusKey bmk;
for (int k = 0; k < 14; k++)
{
int pitch = whitePitch[k];
int ixPos = k * 20;
mk = new MusKey(pitch, ixPos, yLoc);
mk.MouseDown += new MouseEventHandler(this.button1_MouseDown);
mk.MouseUp += new MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(mk);
}
int xOffs = 20;
int[] blackPitch = { 2, 4, 7, 9, 11, 14, 16, 19, 21, 23 };
int[] xPos = { 10, 30, 70, 110, 150, 170, 210, 230, 250 };
const int yPosBlack = 50;
for (int k = 0; k < 10; k++)
{
int pitch = blackPitch[k];
int ixPos = xPos[k];
bmk = new BlackMusKey(pitch, ixPos, yPosBlack);
bmk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown); //create event MouseDown
bmk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp); //create event MouseUp
this.panel1.Controls.Add(bmk);
this.panel1.Controls[this.panel1.Controls.Count - 1].BringToFront();
}
}
SoundPlayer sp = new SoundPlayer();
int count1;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk)
{ //true for the specific key pressed on the Music Keyboard
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = true; //variable of the Timer component
count = 0; //incremented by the timer1_Tick event handler
timer1.Start();
sp.SoundLocation = (mk.getMusicNote() + ".wav"); //might need to convert ToString() ??
sp.Play();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count = count++;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk) //true for the specific key pressed on the Music Keyboard
{
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = false;
sp.Stop();
string bNoteShape = null;
int duration = 0;
if (count >= 16)
{
bNoteShape = "SemiBreve";
duration = 16;
}
if (count >= 8 && count <= 15)
{
bNoteShape = "DotMinim";
duration = (8 + 15) / 2;
}
if (count >= 4 && count <= 7)
{
bNoteShape = "Crotchet";
duration = (4 + 7) / 2;
}
if (count >= 2 && count <= 3)
{
bNoteShape = "Quaver";
duration = (2 + 3) / 2;
}
if (count >= 1)
{
bNoteShape = "Semi-Quaver";
duration = 1;
}
MusicNote mn = new MusicNote(mk.getMusicNote(), duration, bNoteShape); //music note construction
// mn.Location = new Point(xLoc, yLoc);
//this.panel2.Controls.Add(this.mn); //adding MusicNote component to MusicStaff (panel2) collection
xLoc = xLoc + 15;
}
}
}
}
private void function(object sender, PaintEventArgs e)
{
panel1.Show();
panel1.Visible = true;
panel1.BackColor = Color.Blue;
panel1.Size = new Size(5, 5);
panel1.Location = new Point(3, 3);
this.Controls.Add(panel1);
this.Controls.Add(button1);
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
Form 1 [designer] Class:
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load_1);
this.ResumeLayout(false);
}
#endregion
}
Music Note Class
class MusicNote
{
public int notepitch;
public String noteshape;
public int noteduration;
enum accid { sharp, flat, sole };
bool dragging = false;
System.Timers.Timer timer1 = new System.Timers.Timer();
public MusicNote(int iNotepitch, int iDuration, String iBnoteShape)
{
notepitch = iNotepitch;
noteduration = iDuration;
noteshape = iBnoteShape;
}
bool timeron = false;
bool changenote = false;
public static int start = 0;
//public void click(object sender, MouseEventArgs e) { }
//public void RightPress(object sender, MouseEventArgs e) { }
}
}
Black Music Key Class
class BlackMusKey : MusKey
{
public BlackMusKey(int iNote, int x, int y) : base(iNote, x, y)
{
this.BackColor = Color.Black;
this.Size = new System.Drawing.Size(20, 60);
}
}
Program Class
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
According to Form1 class code, there is constructor missing. Please add proper constructor with InitializeComponent() method call. It can be added anywhere in class body.
Code snippet:
public partial class Form1 : Form
{
[...] //your objects declarations
public Form1()
{
InitializeComponent();
}
[...] //rest of your code
}

Moving picture box fast causes flickering C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to move a picture box fast as it is representing a bullet. However, there is a flickering effect and it obscures the image and it is very hard to see the bullet move. I have tried to use double buffering and Invalidating the picture box before its moved but to no avail. Any suggestions? Maybe im using double buffering wrong? (I have it set to be enabled when the form is loaded.)
Code
On the Form:
public void Shoot(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
PictureBox bulletImage = new PictureBox();
DoubleBuffered = true;
StandardBullet bullet = new StandardBullet(PB_CHARA.Location.X, PB_CHARA.Location.Y, FRM_GAME.MousePosition.X, FRM_GAME.MousePosition.Y, this.ClientRectangle, bulletImage);
Controls.Add(bulletImage);
}
}
Within the Standard Bullet class:
public class StandardBullet
{
public string ImageName = "DataBaseMod.Properties.Resources.StandardBullet_3x";
public int sizeX = 15;
public int sizeY = 19;
public int x = 0;
public int y = 0;
int charaPostitionX;
int charaPostitionY;
PictureBox bulletPoint;
public int[] vector = new int[2];
private System.Timers.Timer bulletTimer;
private System.Timers.Timer RemoveTimer;
System.Drawing.Rectangle FRMBounds;
//public delegate void UpdateControlsDelegate();
public StandardBullet(int charaPostiX, int charaPostiY, int MousePostiX, int MousePostiY, System.Drawing.Rectangle FRMboundaries, PictureBox bulletImage)
{
FRMBounds = FRMboundaries;
bulletPoint = bulletImage;
bulletPoint.Name = ImageName;
string filename = ImageName;
bulletPoint.BackgroundImage = DataBaseMod.Properties.Resources.StandardBullet_3x;
var size = new System.Drawing.Size(sizeX, sizeY);
bulletPoint.Size = size;
bulletPoint.BackgroundImageLayout = ImageLayout.Stretch;
charaPostitionX = charaPostiX;
charaPostitionY = charaPostiY;
x = charaPostiX;
y = charaPostiY;
vector[0] = charaPostiX - MousePostiX;
vector[1] = charaPostiY - MousePostiY;
vectorCalc();
bulletTimer = new System.Timers.Timer(10);
RemoveTimer = new System.Timers.Timer(100);
bulletTimer.Elapsed += TickHandler;
bulletTimer.AutoReset = true;
bulletTimer.Enabled = true;
RemoveTimer.Elapsed += removeTickHandler;
RemoveTimer.Enabled = true;
RemoveTimer.AutoReset = true;
}
public void TickHandler(object sender, ElapsedEventArgs e)
{
x = x + vector[0];
y = y + vector[1];
moveBullet();
}
public void removeTickHandler(object sender, ElapsedEventArgs e)
{
RemoveBullet();
}
public void moveBullet()
{
bulletPoint.BeginInvoke(new MethodInvoker(() => { bulletPoint.Location = new System.Drawing.Point(x, y); }));
}
public void vectorCalc()
{
if (vector[0] >= 1)
{
vector[0] = -10;
}
else if (vector[0] <= -1)
{
vector[0] = 10;
}
if (vector[1] >= 1)
{
vector[1] = -10;
}
else if (vector[1] <= -1)
{
vector[1] = 10;
}
}
public void RemoveBullet()
{
if (
(FRMBounds.Left >= bulletPoint.Bounds.Left) ||
( FRMBounds.Right <= bulletPoint.Bounds.Right) ||
(FRMBounds.Top >= bulletPoint.Bounds.Top) ||
(FRMBounds.Bottom <= bulletPoint.Bounds.Bottom)
)
{
Death();
return;
}
}
public void Death()
{
try
{
bulletTimer.Enabled = false;
bulletPoint.Invoke(new MethodInvoker(() => { FRM_GAME.KillBullet(bulletPoint); }));
RemoveTimer.Enabled = false;
}
catch(Exception e)
{
}
}
}
Thanks!
EDIT: I am going to remove this as i think the error may have been casued by my computer. I had two other games running whilst this one and i think this may have caused the poor rendering. Ran my code this morning and everything is fine. Sorry for this.
Using WinForms for dynamic graphics purposes is not a good idea. Instead of controls, try using Graphics and draw desired object on form (or panel or anywhere you want to).

How do I display values under the cursor in the second form?

I draw a candlestick chart from the file data.
Create a new form(second form) when you click the button in which you want to display:
time, high, low, open, close.
namespace stock5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.Load += new System.EventHandler(this.CandleStick_Load);
}
private void CandleStick_Load(object sender, EventArgs e)
{
CHART();
}
public void CHART()
{
*************************************************
//The code reads the data from the file is skipped.
chart1.Series.Clear();
Series price = new Series("price");
chart1.Series.Add(price);
chart1.ChartAreas[0].CursorX.IsUserEnabled = true;
chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
chart1.ChartAreas[0].AxisY.IsStartedFromZero = false;
chart1.Series["price"].ChartType = SeriesChartType.Candlestick;
chart1.Series["price"]["OpenCloseStyle"] = "Triangle";
chart1.Series["price"]["ShowOpenClose"] = "Both";
chart1.Series["price"]["PointWidth"] = "2.0";
chart1.Series["price"]["PriceUpColor"] = "Blue";
chart1.Series["price"]["PriceDownColor"] = "Red";
chart1.Series["price"].BorderColor = Color.Black;
chart1.Series["price"]["MaxPixelPointWidth"] = "2.0";
for (i = 0; i < count - 1; i++)
{
chart1.Series["price"].Points.AddXY(index[i], mass[i, 1], mass[i, 2], mass[i, 0], mass[i, 3]);//index, high, low, open, close
}
int INDEX = 0;
foreach (DataPoint point in chart1.Series["price"].Points)
{
point.AxisLabel = nums[INDEX].ToString();//Replacing the index values for the time(To avoid empty values when markets are closed on weekends)
INDEX++;
}
}
}
}
The second form in which you want to print values depending on the location of the cursor.
private void button1_Click(object sender, EventArgs e)
{
Form newForm = new Form();
newForm.Show();
newForm.Width = 170;
newForm.Height = 230;
}
And a passing question: how to get instead of indexes in the form of time?
There is multiple ways you can communicate with first form in time and here is one of it:
I assume your Form is your new form? (I will use it in my example as it is)
For this example i will create custom class (object) which i will be returning to newly created form every 0.2 sec.
So new object would be
public class MyNewObject
{
int Id { get; set; }
string Name { get; set; }
int Speed { get; set; }
}
So class of Form will look like this (at least code which is needed to perform this)
public partial class Form : Form
{
Timer t = new Timer();
private YourFirstForm myFirstForm;
public Form(YourFirstForm form)
{
InitializeComponents();
myFirstForm = form;
t.Interval = 200; //0.2 sec
Thread t1 = new Thread(FirstFormListener);
t1.Start();
}
private void FirstFormListner()
{
Timer t = new Timer();
t.Interval = 200; //0.2 sec
t.Tick += new EventHandler(timer1_Tick);
t.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
MyNewObject someData = myFirstForm.GetSomeData();
MessageBox.Show(someData.Name);
}
}
And inside your first form:
public partial class YourFirstForm : Form
{
string someString = "Some random string";
public YourFirstForm()
{
InitializeComponents();
}
public MyNewObject GetSomeData()
{
MyNewObject mno = new MyNewObject();
mno.Name = "Random name";
mno.Id = 1;
mno.Speed = 200;
return mno;
}
}
This is one way of doing it and i think it is practical since you can adjust interval of thick so set update time (on slower pc set it to lower value for faster you can to faster value). Also updating is done on separate thread so it doesn't affect your UI (freeze) and you can continue with job.

C# one timer for multiple shapes

For a school project I need to make a small game where multiple Ellipses move.
The last one that gets made with my method to make multiple at the same time moves with the timer I make.
How do you make one timer for all the Ellipses.
class EnemyTeam
{
private Ellipse enemy;
private Canvas canvas;
private double xChange = 50, yChange = 50;
public DispatcherTimer enemyTimer;
private char direction = '0';
private Thickness enemyThickness;
public EnemyTeam(Canvas canvas, double startPosition, SolidColorBrush playerBrush)
{
this.canvas = canvas;
DrawTeam(canvas, 40, playerBrush);
enemyTimer.Interval = TimeSpan.FromMilliseconds(100);
enemyTimer.Start();
}
private void DrawBall(SolidColorBrush brush, Canvas canvas,double x,double y)
{
enemy = new Ellipse();
enemy.Stroke = brush;
enemy.Fill = brush;
enemy.Height = 30;
enemy.Width = 30;
enemy.Margin = new Thickness(x,y, 0, 0);
enemyTimer = new DispatcherTimer();
enemyThickness = enemy.Margin;
canvas.Children.Add(enemy);
enemyTimer.Tick += enemyTimer_Tick;
}
void enemyTimer_Tick(object sender, EventArgs e)
{
if (enemyThickness.Left >= canvas.Width - 100)
{
GoDown();
direction = '1';
}
if (enemyThickness.Left <= 0 + 20)
{
GoDown();
direction = '0';
}
MoveTeam(enemy);
}
private void MoveTeam(Ellipse enemy)
{
enemyThickness = enemy.Margin;
if (direction == '1')
{
enemyThickness.Left -= xChange;
}
if (direction == '0')
{
enemyThickness.Left += xChange;
}
enemy.Margin = enemyThickness;
}
private void GoDown()
{
enemyThickness.Top += yChange;
enemy.Margin = enemyThickness;
}
}
Instead of initializing and assigning event handler in DrawBall method, do that in constructor of EnemyTeam class. This is will give you on timer per EnemyTeam object.
Declare enemyTimer as a static field:
class EnemyTeam
{
private static enemyTimer = new DispatcherTimer();
...
The keyword static will make the field shared for the class.
You're making multiple timers and throwing them away. See this line:
enemyTimer = new DispatcherTimer();
Every time you call that, you're making a new timer and throwing away the previous copy that enemyTimer held a reference to. Because enemyTimer.Start() is called after DrawTeam, it's called only on the last-created timer. None of the other timers get started.
But even if the other timers got started, you'd still only see one Ellipse move, because in enemyTimer_Tick you only ever make changes to enemy, which is a class member variable that points to the last Ellipse created.
I would suggest that you only use one timer, that you save all the Ellipses you create in a list for later use, and that in enemyTimer_Tick you update all of those Ellipses by iterating through the list.
EDIT: Here is a copy of your code, reworked a bit to show you what I mean. I don't really understand what you're trying to do with MoveTeam and the enemyThickness variable, so I didn't mess with that stuff. That is to say, this isn't a complete working solution, just an example of the changes I'm suggesting.
using System.Collections.Generic;
class EnemyTeam
{
private List<Ellipse> enemies = new List<Ellipse>();
private Canvas canvas;
private double xChange = 50, yChange = 50;
public DispatcherTimer enemyTimer;
private char direction = '0';
private Thickness enemyThickness;
public EnemyTeam(Canvas canvas, double startPosition, SolidColorBrush playerBrush)
{
this.canvas = canvas;
DrawTeam(canvas, 40, playerBrush);
enemyTimer = new DispatcherTimer();
enemyTimer.Interval = TimeSpan.FromMilliseconds(100);
enemyTimer.Tick += enemyTimer_Tick;
enemyTimer.Start();
}
private void DrawBall(SolidColorBrush brush, Canvas canvas,double x,double y)
{
enemy = new Ellipse();
enemy.Stroke = brush;
enemy.Fill = brush;
enemy.Height = 30;
enemy.Width = 30;
enemy.Margin = new Thickness(x,y, 0, 0);
enemyThickness = enemy.Margin; // what is this supposed to do?
canvas.Children.Add(enemy);
enemies.Add(enemy);
}
void enemyTimer_Tick(object sender, EventArgs e)
{
foreach (Ellipse enemy in enemies)
{
if (enemyThickness.Left >= canvas.Width - 100)
{
GoDown();
direction = '1';
}
if (enemyThickness.Left <= 0 + 20)
{
GoDown();
direction = '0';
}
MoveTeam(enemy);
}
}
private void MoveTeam(Ellipse enemy)
{
enemyThickness = enemy.Margin;
if (direction == '1')
{
enemyThickness.Left -= xChange;
}
if (direction == '0')
{
enemyThickness.Left += xChange;
}
enemy.Margin = enemyThickness;
}
private void GoDown()
{
enemyThickness.Top += yChange;
enemy.Margin = enemyThickness;
}
}

Timer speed automatically increase

I have following code. When I click on the button picturebox move from right to left and top to bottom. When it move to the end of the panel it again start from right to left and top to bottom. Now the problem is, after first completion of picturebox from right to left timer speed gradually increase though i set it to 200 also it seems that, this line myform.counterTop = myform.counterTop + 5; the value 5 also increase gradually. After first round, it increase a little, after second it increase little more and continues like this. Please tell me why this is happening.
namespace Spaceship_Invaders
{
public partial class Form1 : Form
{
private int invaderlanded = 0;
private int invaderstopped = 0;
private int counterfortop = -60;
private int counterforleft = 415;
private int counterTop = -60;
private int counterLeft = 415;
private bool pictureboxclicked = false;
private int timerinterval = 200;
System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
Image myImage = Image.FromFile("image/Untitled6.png");
pictureBox1.Image = myImage;
pictureBox1.Top = counterfortop;
pictureBox1.Left = counterforleft;
}
public class Spaceship
{
Form1 myform;
public Spaceship(Form1 form)
{
myform = form;
}
public void mspaceship()
{
myform.mytimer.Tick += new EventHandler(TimerEventProcessor);
myform.mytimer.Interval = myform.timerinterval;
myform.mytimer.Enabled = true;
myform.mytimer.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
if (myform.pictureboxclicked)
{
myform.mytimer.Interval = 5;
myform.pictureBox1.Top = myform.counterTop;
//myform.pictureBox1.Left = myform.counterLeft;
myform.counterTop = myform.counterTop - 5;
if (myform.counterTop <-60)
{
//myform.pictureBox1.Enabled = false;
//myform.pictureBox1.Hide();
myform.pictureboxclicked = false;
myform.mytimer.Interval = myform.timerinterval;
myform.counterLeft = 415;
myform.counterTop = -60;
myform.mytimer.Stop();
}
} else {
if (myform.counterTop > 370 || myform.counterLeft < 1)
{
//myform.pictureBox1.Enabled = false;
//myform.pictureBox1.Hide();
myform.invaderlanded++;
myform.textBox2.Text = myform.invaderlanded.ToString();
myform.counterLeft = 415;
myform.counterTop = -60;
myform.pictureboxclicked = false;
myform.mytimer.Interval = myform.timerinterval;
myform.mytimer.Stop();
} else {
myform.pictureBox1.Top = myform.counterTop;
myform.pictureBox1.Left = myform.counterLeft;
myform.counterTop = myform.counterTop + 5;
myform.counterLeft = myform.counterLeft - 5;
}
}
}
}
private void button4_Click(object sender, EventArgs e)
{
Spaceship myspaceship = new Spaceship(this);
myspaceship.mspaceship();
}
Every time you call mspaceship(), you add another event handler to the timer.
The second time you click it, you have two event handlers which each move by 5 pixels.
Instead, you should only add the handler once.

Categories

Resources