下面是一个简单的 C# 示例代码,用于绘制鼠标的移动轨迹:
using System;
using System.Drawing;
using System.Windows.Forms;
public class MouseDrawForm : Form
{
private Point previousPoint;
public MouseDrawForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// MouseDrawForm
//
this.ClientSize = new System.Drawing.Size(800, 600);
this.Name = "MouseDrawForm";
this.Text = "Mouse Draw";
this.ResumeLayout(false);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MouseDrawForm_MouseMove);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.MouseDrawForm_Paint);
}
private void MouseDrawForm_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Black, 2);
g.DrawLine(pen, previousPoint, e.Location);
previousPoint = e.Location;
g.Dispose();
}
}
private void MouseDrawForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
}
[STAThread]
public static void Main()
{
Application.Run(new MouseDrawForm());
}
}
这个示例代码创建了一个继承自 Form
的 MouseDrawForm
类,用于绘制鼠标的移动轨迹。在 MouseDrawForm
的构造函数中,设置窗体的大小和标题。然后,通过重写 MouseDrawForm_MouseMove
方法,在鼠标移动时获取鼠标的当前位置,并在窗体上绘制一条线段,连接上一个位置和当前位置。在 MouseDrawForm_Paint
方法中设置了绘图的平滑模式。
在 Main
方法中创建了一个 MouseDrawForm
实例,并使用 Application.Run
方法运行应用程序的消息循环,以便处理窗体的事件。