Answer the question
In order to leave comments, you need to log in
How to implement C# drawing movement?
Tell me the reason why the movement with the help of the button works and with the help of the buttons it does not?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab2_9
{
public partial class Form1 : Form
{
int s = 0;
int n = 0;
public Form1()
{
InitializeComponent();
}
public void pictureBox1_Paint(object sender, PaintEventArgs e)
{
drawRectangle(e.Graphics);
}
void drawRectangle(Graphics g)
{
Pen blackGreen = new Pen(Color.Green, 3);
Rectangle rect = new Rectangle(50, 50, 100, 100);
g.DrawLine(blackGreen, new Point(s, n), new Point(s, 60 + n));
g.DrawLine(blackGreen, new Point(s + 50, n), new Point(s + 50, 60 + n));
g.DrawLine(blackGreen, new Point(s + 25, 30 + n), new Point(s + 50, n));
g.DrawLine(blackGreen, new Point(s + 25, 30 + n), new Point(s, n));
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
for (int i = 0; i < 10; i++)
{
n += 10;
Thread.Sleep(100);
pictureBox1.Refresh();
}
break;
case Keys.Down:
for (int i = 0; i < 10; i++)
{
n -= 10;
Thread.Sleep(100);
pictureBox1.Refresh();
}
break;
case Keys.Right:
for (int i = 0; i < 10; i++)
{
s += 10;
Thread.Sleep(100);
pictureBox1.Refresh();
}
break;
case Keys.Left:
for (int i = 0; i < 10; i++)
{
s -= 10;
Thread.Sleep(100);
pictureBox1.Refresh();
}
break;
default:
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
s += 10;
Thread.Sleep(50);
pictureBox1.Refresh();
}
}
}
}
Answer the question
In order to leave comments, you need to log in
What exactly doesn't work?
The methods are executed synchronously, and until the whole cycle ends, the picture will not be displayed ... or rather, it can and will, but at the request of the operating system.
Add Application.DoEvents() to the loop body. In general, it's crooked, but it will do for the lab. Especially for one where animation in Windows Forms is forced to be done.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question