试图在点击上画矩形
问题描述:
所以我一直在自学c#教程和下面的教程。直到这个时候没有什么大问题。 Bun现在我不能自己找到解决方案。试图在点击上画矩形
所以我列出了一个简单的表单,它应该可以在不同的鼠标点击上创建矩形和吸引点。但是当我运行代码时,没有任何反应。
我无法理解什么是错的..请帮助(=
public partial class Form1 : Form
{
float mRectSize = 50;
List<RectangleF> mRectangles = new List<RectangleF>();
Random rnd = new Random();
PointF mForcePoint = new PointF(-1, -1);
bool mForcePush = false;
int mRandomSeed = 10;
public Form1()
{
InitializeComponent();
Timer timer1 = new Timer();
timer1.Interval = 1;
timer1.Tick += Timer1_Tick;
timer1.Start();
}
private void AddRectangle(PointF pos)
{
mRectangles.Add(new RectangleF(pos.X - mRectSize/2, pos.Y - mRectSize/2, mRectSize, mRectSize));
}
private void AddForcePoint(PointF pos)
{
mForcePoint = pos;
}
private void DrawRectangle(Graphics g, RectangleF rect)
{
Color c = Color.FromArgb(255, rnd.Next(255), rnd.Next(255), rnd.Next(255));
g.FillRectangle(new SolidBrush(c), rect);
}
private PointF RandomiseDirection(PointF dir)
{
dir.X += rnd.Next(2 * mRandomSeed) - mRandomSeed;
dir.Y += rnd.Next(2 * mRandomSeed) - mRandomSeed;
return dir;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
foreach (RectangleF rect in mRectangles)
{
DrawRectangle(g, rect);
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
AddRectangle(e.Location);
//MessageBox.Show("test");
Invalidate();
}
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
AddForcePoint(e.Location);
}
if (e.Button == System.Windows.Forms.MouseButtons.Middle)
{
mForcePush = !mForcePush;
}
}
private void Timer1_Tick(object sender, EventArgs e)
{
if (mForcePoint.X != -1 && mForcePoint.Y != -1)
{
for (int i = 0; i < mRectangles.Count; i++)
{
RectangleF rect = mRectangles[i];
PointF direction = new PointF(mForcePoint.X - rect.Location.X, mForcePoint.Y - rect.Location.Y);
direction = RandomiseDirection(direction);
if (mForcePush)
{
rect.Location = new PointF(rect.Location.X - direction.X * 0.1f, rect.Location.Y - direction.Y * 0.1f);
}
else
{
rect.Location = new PointF(rect.Location.X + direction.X * 0.1f, rect.Location.Y + direction.Y * 0.1f);
}
mRectangles[i] = rect;
}
Invalidate();
}
}
}
}
答
所以答案很简单。我谴责的教程,因为没有这样提什么使以往任何时候。
我只是需要加入(我鼠标点击方法的名称) 鼠标点击+ = 要 私人Form1中()
这似乎是学习调试的好时机。尝试设置一些断点,看看发生了什么。 – Blorgbeard
mForcePoint是否被更改过? –
它假设改按人民币..但还是一无所获。 –