C# Moving Label in Windows Forms

Jan 31 2019 2:01 AM
Hallo dear Team,
 
for a new project I have to develop a a moving Label on a WinForm.
I've already started like this (here the code):
  1. namespace FormsMovingLabel  
  2. {  
  3. public partial class Form1 : Form  
  4. {  
  5. int x, cnt = 0;  
  6. float y = 1f;  
  7. public Form1()  
  8. {  
  9. InitializeComponent();  
  10. }  
  11. private void Form1_Load(object sender, EventArgs e)  
  12. {  
  13. label1.Top = 10;  
  14. label1.ForeColor = Color.RoyalBlue;  
  15. label1.Font = new Font("", 26, FontStyle.Italic | FontStyle.Bold);  
  16. timer1.Interval = 1;  
  17. timer1.Start();  
  18. }  
  19. private void timer1_Tick(object sender, EventArgs e)  
  20. {  
  21. label1.SetBounds(x, (int)y, 15, 20);  
  22. if (cnt == 0)  
  23. {  
  24. x++;  
  25. y = y + 0.9f;  
  26. }  
  27. if (cnt == 1)  
  28. {  
  29. x--;  
  30. y = y - 0.9f;  
  31. }  
  32. if (x == 300)  
  33. {  
  34. cnt = 1;  
  35. }  
  36. if (x == 1)  
  37. {  
  38. cnt = 0;  
  39. }  
  40. }  
  41. }  
  42. }
The code works and the label moves diagonally
 but I have a couple of questions because I would like to limit the moving at 10 times.
Any Tip? I' ve already tried with for-loop but the programm doesnt work anymore.
1)Maybe do I need  for-loop?
If yes, how shall I use the for-loop? If you consider that:
 
  1. if (cnt == 0)  
  2. {  
  3. x++;  
  4. y = y + 0.9f;  
  5. }  
  6. if (cnt == 1)  
  7. {  
  8. x--;  
  9. y = y - 0.9f;  
  10. }  
  11. if (x == 300)  
  12. {  
  13. cnt = 1;  
  14. }  
  15. if (x == 1)  
  16. {  
  17. cnt = 0;  
The Label should move with coordinates from 0 to 300.
2) If you look at the code, is it enough that x ==300? 
 
Thanks in advance for your help.
 

Answers (3)