当鼠标移到面板上时,我试图画一条垂直线:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
Panel panel = sender as Panel;
if (panel != null)
{
using (Graphics g = panel.CreateGraphics())
{
using (Pen pen = new Pen(Color.Red))
{
g.DrawLine(pen, e.X, 0, e.X, panel.Height);
}
}
panel.Invalidate(true);
}
}
但是,没有什么被吸入。
我在做什么错了?
答案 0 :(得分:3)
所有GDI绘图都必须在.Paint()
参数内提供的Graphics
对象的PaintEventArgs
事件内完成。使用.MouseMove()
存储鼠标值,并触发绘制事件。
尝试一下:
public partial class Form1 : Form
{
Point mouse;
MouseButtons buttons;
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (sender is Panel panel)
{
var g = e.Graphics;
g.DrawLine(Pens.Red, mouse.X, 0, mouse.X, panel.Height);
}
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
mouse=e.Location;
buttons=e.Button;
panel1.Refresh();
}
}
这是结果: