为了实现在窗口内绘制以鼠标为中心的十字线,鼠标移动时十字线也移动,类似截图软件或者股票软件里面定位的东东.
自己试着写了一个,但是效率不是很高,cpu占用率很高,而且动鼠标的时候明显感觉有延迟.谁能给个最优解或是说说思路是怎样的?
我用两个Label实现快速画线,CPU基本无占用,楼主在你窗体加入下列代码试试
Label lblHR;
Label lblVT;
private void Form1_Load(object sender, EventArgs e)
{
lblHR = new Label();
lblVT = new Label();
this.Controls.Add(lblHR);
this.Controls.Add(lblVT);
lblHR.Text = "";
lblHR.AutoSize = false;
lblHR.Width = this.Width;
lblHR.Height = 1;
lblHR.BackColor = Color.Black;
lblHR.Left = 0;
lblHR.Anchor = AnchorStyles.Left | AnchorStyles.Right;
lblHR.BringToFront();
lblVT.Text = "";
lblVT.AutoSize = false;
lblVT.Height = this.Height;
lblVT.Width = 1;
lblVT.BackColor = Color.Black;
lblVT. = 0;
lblVT.Anchor = AnchorStyles. | AnchorStyles.Bottom;
lblVT.BringToFront();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
lblHR. = e.Y;
lblVT.Left = e.X;
}
private Point currentPoint = new Point(0,0);
private Pen pen = new Pen(Color.Black);
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.X != currentPoint.X || e.Y != currentPoint.Y)
{
currentPoint = new Point(e.X,e.Y);
this.Invalidate(true);
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawLine(pen, 0, currentPoint.Y, this.Width, currentPoint.Y);
e.Graphics.DrawLine(pen, currentPoint.X , 0, currentPoint.X, this.Height);
}
private void Form1_Closed(object sender, System.EventArgs e)
{
pen.Dispose();
}