Chris Meller
Chris Meller

Reputation: 189

How to change the cursor on hover in C#

I can't find out on how I can change my cursor to a "pointer" or whatever it's called while hovering an image.

I have tried with MouseOver but I can't get it to work. Here's my current code;

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

However, the cursor doesn't change.

Upvotes: 13

Views: 25089

Answers (6)

TaW
TaW

Reputation: 54433

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 ImageArea when changing the Image or the SizeMode or the Size of The PictureBox.

Upvotes: 8

Tobias Meyer
Tobias Meyer

Reputation: 71

For any PowerShell/Windows Forms programmers:

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

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

Upvotes: 6

Timon Post
Timon Post

Reputation: 2889

  1. You can use the mouse down event change the cursor
  2. than with the mouse move event check if location the same as image
  3. Than wait for the mouse up event and set the default cursor

    • Or just set the property for the cursor

Upvotes: 1

Pepernoot
Pepernoot

Reputation: 3609

Instead of using Cursor.Current use image_Phone.Cursor = Cursors.Hand;

Upvotes: 2

rpeshkov
rpeshkov

Reputation: 5047

Set appropriate cursor in control properties window.

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

enter image description here

Upvotes: 31

Scott Perham
Scott Perham

Reputation: 2470

In WinForms (assumption made by the tag) - there is a Cursor property on the PicutureBox control... (It's actually on Control) try setting that?

Upvotes: 1

Related Questions