下面是一個簡單的 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
方法運行應用程序的消息循環,以便處理窗體的事件。