如何在C#中实现鼠标悬停时更改光标

13

我不知道如何在鼠标悬停在图像上时将光标更改为“指针”或其他名称。

我尝试使用MouseOver,但无法使其工作。这是我的当前代码;

private void image_Phone_MouseOver(object sender, EventArgs e)
{
    Cursor.Current = Cursors.Hand;
}

然而,光标并没有改变。


1
你尝试过处理MouseEnter和MouseLeave事件,并将光标分别设置为Hand和Default吗? - Scott Perham
我确实尝试使用MouseEnter,但是在谷歌搜索后它也无法工作。 - Chris Meller
设置光标后,请调用Application.DoEvents();。否则消息循环将被阻塞...使用此方法将会传送消息... 或者尝试 image_phone.Cursor = Cursors.Hand; - Trevor
我也试过了,@Zaggler。 - Chris Meller
@Chris Meller 你试过哪一个,是 DoEvents 还是实际设置 picturebox 的光标? - Trevor
6个回答

31

在控件属性窗口中设置适当的光标。

以下是为picturebox设置“手形”光标的示例。

输入图像描述


我认为这是最好的方法,或者如果你在流式布局中动态创建PictureBoxes,则通过编程方式设置其光标属性。我发现MouseEnter/Leave更改存在问题,它们无法正确触发,在MouseHover事件中,光标开始在手形和默认状态之间闪烁。 - Jonas

8
这是一种在鼠标悬停在实际图像上时更改光标的方法:

enter image description here

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    pictureBox1.Cursor = ImageArea(pictureBox1).Contains(e.Location) ?
                                                Cursors.Hand : Cursors.Default;
}

Rectangle ImageArea(PictureBox pbox)
{
    Size si = pbox.Image.Size;
    Size sp = pbox.ClientSize;
    float ri = 1f * si.Width / si.Height;
    float rp = 1f * sp.Width / sp.Height;
    if (rp > ri)
    {
        int width = si.Width * sp.Height / si.Height;
        int left = (sp.Width - width) / 2;
        return new Rectangle(left, 0, width, sp.Height);
    }
    else
    {
        int height = si.Height * sp.Width / si.Width;
        int top = (sp.Height - height) / 2;
        return new Rectangle(0, top, sp.Width, height);
    }
}

请注意,在更改ImageSizeModeSize时,您需要重新计算PictureBoxImgArea

6

对于任何 PowerShell/Windows Forms 程序员:

您可以将此用于表单中的基本每个元素:

$pictureBox1.Add_MouseHover({ $this.Cursor = "Hand" })

2

不要使用Cursor.Current,而是使用image_Phone.Cursor = Cursors.Hand;。


这也行不通,这是截图的样子;http://prntscr.com/chk1k3 - Chris Meller

1
  1. 您可以使用鼠标按下事件更改光标
  2. 然后使用鼠标移动事件检查位置是否与图像相同
  3. 然后等待鼠标松开事件并设置默认光标

    • 或者只需设置光标属性

1
在WinForms中(假设标签所述),PictureBox控件上有一个Cursor属性...(实际上在Control上)尝试设置它?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接