akinuri
akinuri

Reputation: 12027

How to set a custom cursor?

How do I set a custom cursor? I've read several questions and answers and couldn't find anything useful.

I'm creating an image viewer, and currently working on the pan functionality. I have a function that runs after any scale/zoom is applied to a PictureBox:

private void CheckOverflow()
{
    if (ImageBox.Width > BottomPanel.Width || ImageBox.Height > BottomPanel.Height)
    {
        BottomPanel.Cursor = Cursors.Hand; // set a custom cursor "pannable"
    }
    else if (BottomPanel.Cursor != Cursors.Default)
    {
        BottomPanel.Cursor = Cursors.Default;
    }
}

If the PictureBox overflows Panel, it is pannable. Right now, I'm using Windows cursors and it's working fine, but I want to change the Hand cursor into a custom one.

I have a custom cursor named pannable.cur. I've added it to the project through Project->Properties->Resources window, and changed its Build Action property into Embedded Resource.

Now, how and where should I create the cursor? I believe this is how:

Cursor Pannable = new Cursor(GetType(), "pannable.cur");

but where should I place this? If I place this inside CheckOverflow, it'll be created over and over again. Besides that, it doesn't work. I get the following error:

enter image description here

I'll be creating two cursors (pannable and panning), once, and change the contols' cursors back and forth.

What should I do?

Source code is available at Github.

Upvotes: 0

Views: 731

Answers (2)

Gutiman
Gutiman

Reputation: 81

for VS 2019:

someControl.Cursor = new Cursor(Properties.Resources.yourPNG.GetHicon());

don't forget to add 'yourPNG.png' with any transparency you'd like to your project as a resource.

Upvotes: 0

Lucax
Lucax

Reputation: 407

Maybe try:

using (MemoryStream stream = new MemoryStream(Properties.Resources.pannable))
{
    BottomPanel.Cursor = new Cursor(stream);
}

Properties.Resource.pannable returns a byte array, MemoryStream turns it into a stream so you can use the Cursor(Stream) constructor. See here (https://msdn.microsoft.com/en-us/library/system.windows.forms.cursor(v=vs.110).aspx)

If you don't care about disposing, then just use:

BottomPanel.Cursor = new Cursor(new MemoryStream(Properties.Resources.pannable));

Upvotes: 3

Related Questions