Winforms: calling entry form function from a different class
Posted
by
samy
on Stack Overflow
See other posts from Stack Overflow
or by samy
Published on 2012-03-18T16:51:17Z
Indexed on
2012/03/18
17:56 UTC
Read the original article
Hit count: 376
I'm kinda new to programming and got a question on what is a good practice.
I created a class that represents a ball and it has a function Jump()
that use 2 timers and get the ball up and down.
I know that in Winforms you got to call Invalidate()
every time you want to repaint the screen, or part of it. I didn't find a good way to do that, so I reference the form in my class, and called Invalidate()
inside my ball class every time I need to repaint to ball movement.
(this works but I got a feeling that this is not a good practice)
Here is the class I created:
public class Ball
{
public Form1 parent;//----> here is the reference to the form
public Rectangle ball;
Size size;
public Point p;
Timer timerBallGoUp = new Timer();
Timer timerBallGDown = new Timer();
public int ballY;
public Ball(Size _size, Point _p)
{
size = _size;
p = _p;
ball = new Rectangle(p, size);
}
public void Jump()
{
ballY = p.Y;
timerBallGDown.Elapsed += ballGoDown;
timerBallGDown.Interval = 50;
timerBallGoUp.Elapsed += ballGoUp;
timerBallGoUp.Interval = 50;
timerBallGoUp.Start();
}
private void ballGoUp(object obj,ElapsedEventArgs e)
{
p.Y++;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y >= ballY + 50)
{
timerBallGoUp.Stop();
timerBallGDown.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 1
}
private void ballGoDown(object obj, ElapsedEventArgs e)
{
p.Y--;
ball.Location = new Point(ball.Location.X, p.Y);
if (p.Y <= ballY)
{
timerBallGDown.Stop();
timerBallGoUp.Start();
}
parent.Invalidate(); // here i call parent.Invalidate() 2
}
}
I'm wondring if there is a better way to do that?
(sorry for my english)
© Stack Overflow or respective owner