自定义控件类CheckerChild,继承自UserControl类:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CsDev
{
//自定义自控件
class CheckerChild:UserControl
{
bool bChecked = false;
public CheckerChild()
{
ResizeRedraw = true;
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
bChecked = !bChecked;
Invalidate();
}
protected override void OnKeyDown(KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.Enter:
case Keys.Space:
OnClick(new EventArgs());
break;
}
}
protected override void OnGotFocus(EventArgs e)//获得焦点
{
Invalidate();
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)//失去焦点
{
Invalidate();
base.OnGotFocus(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics grph = e.Graphics;
Pen pen = new Pen(Color.Red);
grph.DrawRectangle(pen, ClientRectangle);
if(bChecked)//画X
{
grph.DrawLine(pen,0,0,ClientSize.Width,ClientSize.Height);
grph.DrawLine(pen,0,ClientSize.Height,ClientSize.Width,0);
}
if (Focused)//以前景色来清除X
{
grph.DrawRectangle(new Pen(ForeColor,5),ClientRectangle);
}
base.OnPaint(e);
}
}
}
使用自定义控件:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CsDev
{
class CheckerWithChild:Form
{
const int xNum = 5;
const int yNum = 4;
CheckerChild[,] acntlChild;//定义自定义控件变量
static void Main()
{
Application.Run(new CheckerWithChild());
}
public CheckerWithChild()
{
Text = "CheckerWithChild";
CreateChildren();
OnResize(EventArgs.Empty);
}
protected virtual void CreateChildren()
{
acntlChild=new CheckerChild[yNum,xNum];
//添加自定义控件
for(int y=0;y<yNum;y++)
for (int x = 0; x <xNum; x++)
{
acntlChild[y, x] = new CheckerChild();
acntlChild[y, x].Parent = this;
}
}
protected override void OnResize(EventArgs e)
{
int cxBlock = ClientSize.Width / xNum;
int cyBlock = ClientSize.Height / yNum;
for (int y = 0; y < yNum; y++)
for (int x = 0; x < xNum; x++)
{
acntlChild[y, x].Location = new Point(x*cxBlock,y*cyBlock);
acntlChild[y, x].Size = new Size(cxBlock,cyBlock);
}
}
}
}
效果图: