所以我一直在自学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();
}
}
}
}
答案 0 :(得分:1)
所以答案很简单。而且我责备了一个教程,因为没有提到这个曾经如此。
我只需要添加 MouseClick + =(我的MouseClick方法的名称) 至 私人Form1()