日期:2014-05-18 浏览次数:20954 次
using System;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : Form
{
ToolTip toolTip1 = new ToolTip();
int lastHit = -1;
Rectangle[] cars = new Rectangle[]{
new Rectangle(100,50, 32,32),
new Rectangle(200,50, 32,32),
new Rectangle(200,100,32,32),
new Rectangle(100,180,32,32),
new Rectangle(10,50,32,32),
};
protected override void OnMouseMove(MouseEventArgs e)
{
int hit = -1;
for(int i=0; i<cars.Length; i++)
{
if (cars[i].Contains(e.Location))
{
hit = i;
break;
}
}
this.Cursor = (hit >= 0) ? Cursors.Help : Cursors.Default;
if (hit>=0 && hit != lastHit)
{
toolTip1.Show( "car " + hit, this, e.Location, 2000);
}
lastHit = hit;
}
protected override void OnPaint(PaintEventArgs e)
{
using (Graphics g = e.Graphics)
{
foreach (Rectangle rect in cars)
{
g.FillRectangle(Brushes.LightCoral, rect);
}
}
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
------解决方案--------------------
1、你可以用Cursor的静态属性Cursor.Position来得到当前鼠标的屏幕位置,不过你得把它转化
成picturebox1中的坐标才好比较:
Point p = picturebox1.PointToClient( Cursor.Position );
2、你也可以处理MouseMove事件,而不用MouseHover事件。在MouseMove事件中,就有鼠标的location了。