11.C#编程学习——捕获鼠标
源码
//---------------------------------------
// MouseWeb.cs ?2001 by CharlesPetzold
//---------------------------------------
usingSystem;
usingSystem.Drawing;
usingSystem.Windows.Forms;
classMouseWeb : Form
{
Point ptMouse = Point.Empty;
publicstaticvoid Main()
{
Application.Run(newMouseWeb());
}
public MouseWeb()
{
Text = "Mouse Web";
BackColor = SystemColors.Window;
ForeColor = SystemColors.WindowText;
ResizeRedraw = true;
}
protectedoverridevoid OnMouseMove(MouseEventArgs mea)
{
Graphics grfx = CreateGraphics();
DrawWeb(grfx, BackColor, ptMouse);
ptMouse = newPoint(mea.X, mea.Y);
DrawWeb(grfx, ForeColor, ptMouse);
grfx.Dispose();
}
protectedoverridevoid OnPaint(PaintEventArgs pea)
{
DrawWeb(pea.Graphics, ForeColor,ptMouse);
}
void DrawWeb(Graphicsgrfx, Color clr, Point pt)
{
int cx = ClientSize.Width;
int cy = ClientSize.Height;
Pen pen = newPen(clr);
grfx.DrawLine(pen, pt, newPoint(0,0));
grfx.DrawLine(pen, pt, newPoint(cx/ 4, 0));
grfx.DrawLine(pen, pt, newPoint(cx/ 2, 0));
grfx.DrawLine(pen, pt, newPoint(3* cx / 4, 0));
grfx.DrawLine(pen, pt, newPoint(cx,0));
grfx.DrawLine(pen, pt, newPoint(cx,cy / 4));
grfx.DrawLine(pen, pt, newPoint(cx,cy / 2));
grfx.DrawLine(pen, pt, newPoint(cx,3 * cy / 4));
grfx.DrawLine(pen, pt, newPoint(cx,cy));
grfx.DrawLine(pen, pt, newPoint(3* cx / 4, cy));
grfx.DrawLine(pen, pt, newPoint(cx/ 2, cy));
grfx.DrawLine(pen, pt, newPoint(cx/ 4, cy));
grfx.DrawLine(pen, pt, newPoint(0,cy));
grfx.DrawLine(pen, pt, newPoint(0,cy / 4));
grfx.DrawLine(pen, pt, newPoint(0,cy / 2));
grfx.DrawLine(pen, pt, newPoint(0,3 * cy / 4));
}
}
获取CHECKER
usingSystem;
usingSystem.Drawing;
usingSystem.Windows.Forms;
classChecker : Form
{
protectedconstint xNum = 5; // Number of boxes horizontally
protectedconstint yNum = 4; // Number of boxes vertically
protectedbool[,] abChecked = newbool[yNum,xNum];
protectedint cxBlock, cyBlock;
publicstaticvoid Main()
{
Application.Run(newChecker());
}
public Checker()
{
Text = "Checker";
BackColor = SystemColors.Window;
ForeColor = SystemColors.WindowText;
ResizeRedraw = true;
OnResize(EventArgs.Empty);
}
protectedoverridevoid OnResize(EventArgs ea)
{
base.OnResize(ea); // Or else ResizeRedraw doesn't work
cxBlock = ClientSize.Width / xNum;
cyBlock = ClientSize.Height / yNum;
}
protectedoverridevoid OnMouseUp(MouseEventArgs mea)
{
int x = mea.X / cxBlock;
int y = mea.Y / cyBlock;
if (x < xNum && y < yNum)
{
abChecked[y, x] ^= true;
Invalidate(newRectangle(x* cxBlock, y * cyBlock,
cxBlock,cyBlock));
}
}
protectedoverridevoid OnPaint(PaintEventArgs pea)
{
Graphics grfx = pea.Graphics;
Pen pen = newPen(ForeColor);
for (int y = 0; y < yNum;y++)
for (int x = 0; x < xNum;x++)
{
grfx.DrawRectangle(pen, x *cxBlock, y * cyBlock,
cxBlock, cyBlock);
if (abChecked[y, x])
{
grfx.DrawLine(pen, x *cxBlock, y * cyBlock,
(x + 1) *cxBlock, (y + 1) * cyBlock);
grfx.DrawLine(pen, x *cxBlock, (y + 1) * cyBlock,
(x + 1) * cxBlock, y * cyBlock);
}
}
}
}