public
static
void
Main(
string
[] args)
{
var
panel =
new
MyPanel();
panel.Dock = DockStyle.Fill;
DrawLines(panel);
var
form =
new
Form();
form.Controls.Add(panel);
form.ShowDialog();
}
// 爲了方便,直接在一個函數中完成
private
static
void
DrawLines(Panel panel)
{
// 保存繪製點,爲了簡單,只保存系列個繪製點的座標,
// 根據需要可以加入系列個繪製點間的顏色及線型
var
points =
new
List<Point>();
// 界面重繪
panel.Paint += (sender, args) =>
{
if
(points.Count >= 2)
{
// 繪製出所有繪製點之間的線條,這裏爲了方便,直接將顏色/線型寫入代碼中
// 可以根據需要從界面設置中獲取參數
using
(
var
pen =
new
Pen(Color.Black, 2))
{
args.Graphics.DrawLines(pen, points.ToArray());
}
}
if
(points.Count > 0)
{
// 繪製出最後一個與當前鼠標點之間的線條,這裏爲了方便,直接將顏色/線型寫入代碼中
// 可以根據需要從界面設置中獲取參數
using
(
var
pen =
new
Pen(Color.Red, 2))
{
var
curPostion = panel.PointToClient(Cursor.Position);
pen.DashStyle = DashStyle.DashDot;
args.Graphics.DrawLine(pen, points.Last(), curPostion);
}
}
};
// 鼠標移動時直接要求重繪
panel.MouseMove += (sender, args) => panel.Invalidate();
// 單擊時根據左鍵或是右鍵加入繪製點或是清空所有繪製點,然後重繪
panel.MouseClick += (sender, args) =>
{
if
(args.Button == MouseButtons.Left)
{
points.Add(
new
Point(args.X, args.Y));
}
else
if
(args.Button == MouseButtons.Right)
{
points.Clear();
}
panel.Invalidate();
};
}
}
internal
class
MyPanel : Panel
{
public
MyPanel()
{
// 用雙緩存,繪製時不會閃爍
DoubleBuffered =
true
;
}
}