Tuesday, February 18, 2014

How to use custom cursor from resource?

using System.Runtime.InteropServices;
using System.IO;

namespace Form1
{
    public partial class Form1: Form
    {

        private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(Form1.Properties.Resources.yl_cur);
        private Cursor yellowCursor = LoadCursorFromResource(cursorMemoryStream);
        this.Cursor = yellowCursor;


        [DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern IntPtr LoadCursorFromFile(String str);

        public static Cursor LoadCursorFromResource(System.IO.MemoryStream cursorMemoryStream)
        {      

             using (var fileStream = File.Create(@".\tempCursor.cur"))
             {
                 cursorMemoryStream.CopyTo(fileStream);
             }

             Cursor result = new Cursor(LoadCursorFromFile(@".\tempCursor.cur"));
             File.Delete(@".\tempCursor.cur");

             return result;
        }

No comments:

Post a Comment