How to change the cursor on hover in C#

Set appropriate cursor in control properties window.

Here's an example of setting "Hand" cursor for picturebox.

enter image description here


This is a way to change the cursor when over the actual Image:

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);
    }
}

Note that you will need to re-calculate the ImgArea when changing the Image or the SizeMode or the Size of The PictureBox.


For any PowerShell/Windows Forms programmers:

You can use this for basically every element in your form:

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

Tags:

C#

Winforms