need a simple animation tool

E

Ernst Sauer

Hello,

I have a Form1 with buttons and a partial class Form2 for my drawings.

For scaling the graphic I use a handler in Form1:

private void plusV_Click(object sender, EventArgs e)
{ factorf *= 2; // scaling factor
child.Invalidate(); // Form2 has OnPaint
}

This works fine.
Now I want a simple animation tool, something like that.

private void pluslusV_Click(object sender, EventArgs e)
{ for (int i=1; i<=10; i++)
{ factorf *= 2;
child.Invalidate();
Thread.Sleep(100); // or 1000
}
}

But this handler shows me only the last picture, not 10 in
10 time intervals.

Thanks for help
Ernst
 
A

Arne Vajhøj

I have a Form1 with buttons and a partial class Form2 for my drawings.

For scaling the graphic I use a handler in Form1:

private void plusV_Click(object sender, EventArgs e)
{ factorf *= 2; // scaling factor
child.Invalidate(); // Form2 has OnPaint
}

This works fine.
Now I want a simple animation tool, something like that.

private void pluslusV_Click(object sender, EventArgs e)
{ for (int i=1; i<=10; i++)
{ factorf *= 2;
child.Invalidate();
Thread.Sleep(100); // or 1000
}
}

But this handler shows me only the last picture, not 10 in
10 time intervals.

The GUI first update when the click method return.

There are a few ways to solve that problem.

Example:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace E
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
// the crappy solution
void Button1Click(object sender, EventArgs e)
{
while(true)
{
label1.Text = DateTime.Now.ToString("HH:mm:ss");
System.Threading.Thread.Sleep(1000);
Application.DoEvents();
}
}
// the traditional solution
void Update2()
{
label2.Text = DateTime.Now.ToString("HH:mm:ss");
}
void Run()
{
while(true)
{
if(label2.InvokeRequired)
{
label2.Invoke((Action)(() => Update2()));
}
else
{
Update2();
}
System.Threading.Thread.Sleep(1000);
}
}
void Button2Click(object sender, EventArgs e)
{
(new System.Threading.Thread(Run)).Start();
}
// the win forms solution
void Update3(object sender, EventArgs e)
{
label3.Text = DateTime.Now.ToString("HH:mm:ss");
}
Timer t;
void Button3Click(object sender, EventArgs e)
{
t = new Timer();
t.Interval = 1000;
t.Tick += Update3;
t.Start();
}
// the async solution
async void Button4Click(object sender, EventArgs e)
{
while(true)
{
label4.Text = DateTime.Now.ToString("HH:mm:ss");
await Task.Delay(1000);
}
}
//
void Button5Click(object sender, EventArgs e)
{
Application.Exit();
Environment.Exit(0);
}
}
}

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top