c#生成一个5*5的宫格,并且点击格子变色,求帮助
解决方案
40
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 宫格
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Text = "宫格";
MouseDown += new MouseEventHandler(OnMouseDown);
}
Rectangle[] rects;
protected override void OnLoad(EventArgs e)
{
int d = (Height - 60) / 5;
int x = (Width - d * 5) / 2;
int y = (Height - d * 5) / 4;
rects = new Rectangle[25];
for(var i = 0; i < 5; i++)
{
for(var j = 0; j < 5 ; j++)
{
rects[i * 5 + j] = new Rectangle(x + i * d, y + j * d, d - 2, d - 2);
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
for (var i = 0; i < 5; i++)
{
for (var j = 0; j < 5; j++)
{
g.DrawRectangles(Pens.Black, rects);
}
}
if (fill != Rectangle.Empty) g.FillRectangle(Brushes.Red, fill);
}
Rectangle fill = Rectangle.Empty;
void OnMouseDown(object sender, MouseEventArgs e)
{
foreach (var r in rects)
{
if(r.Contains(e.X, e.Y))
{
fill = r;
Invalidate();
break;
}
}
}
}
}