How to Implement C # winForm custom mouse styles

Source: Internet
Author: User

First: (call the system API)
First, two namespaces are introduced. Copy codeThe Code is as follows: using System. Runtime. InteropServices;
Using System. Reflection;

Import APICopy codeThe Code is as follows: [DllImport ("user32.dll")]
Public static extern IntPtr LoadCursorFromFile (string fileName );
[DllImport ("user32.dll")]
Public static extern IntPtr SetCursor (IntPtr cursorHandle );
[DllImport ("user32.dll")]
Public static extern uint DestroyCursor (IntPtr cursorHandle );

Next, use your mouse style.Copy codeThe Code is as follows: private void Form1_Load (object sender, EventArgs e)
{
Cursor myCursor = new Cursor (Cursor. Current. Handle );
IntPtr colorCursorHandle = LoadCursorFromFile ("my. cur"); // Mouse icon path
MyCursor. GetType (). InvokeMember ("handle", BindingFlags. Public |
BindingFlags. NonPublic | BindingFlags. Instance |
BindingFlags. SetField, null, myCursor,
New object [] {colorCursorHandle });
This. Cursor = myCursor;
}

Method 2: (you do not need to use the API. The mouse style only requires a transparent background image, in png or gif format)
Copy codeThe Code is as follows: public void SetCursor (Bitmap cursor, Point hotPoint)
{
Int hotX = hotPoint. X;
Int hotY = hotPoint. Y;
Bitmap myNewCursor = new Bitmap (cursor. Width * 2-hotX, cursor. Height * 2-hotY );
Graphics g = Graphics. FromImage (myNewCursor );
G. Clear (Color. FromArgb (0, 0, 0, 0 ));
G. DrawImage (cursor, cursor. Width-hotX, cursor. Height-hotY, cursor. Width,
Cursor. Height );
This. Cursor = new Cursor (myNewCursor. GetHicon ());

G. Dispose ();
MyNewCursor. Dispose ();
}

Use this method in the event you want to change the mouse style, for example:Copy codeThe Code is as follows: private void Form1_Load (object sender, EventArgs e)
{
Bitmap a = (Bitmap) Bitmap. FromFile ("myCur.png ");
SetCursor (a, new Point (0, 0 ));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.