Sunday 16 February 2014

Implement Animated cursor using C# Winforms



First you must add three namespaces like below.

using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;


Then write a method (LoadCustomCursor) like given below.
 
public static Cursor LoadCustomCursor(string path)
        {
            IntPtr hCurs = LoadCursorFromFile(path);
            if (hCurs == IntPtr.Zero) throw new Win32Exception();
            var curs = new Cursor(hCurs);
            // Note: force the cursor to own the handle so it gets released properly
            var fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
            fi.SetValue(curs, true);
            return curs;
        }


        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr LoadCursorFromFile(string path);


Sample usage:

private void btnSave_Click(object sender, EventArgs e)
{ 
this.Cursor = LoadCustomCursor(Application.StartupPath + "\\images\\Black and Blue Working in Background.ani");

//Enter your C# Code here

this.Cursor = Cursors.Default;

}

No comments:

Post a Comment