如何创建从位图对象Cursor对象? [英] How do I create a Cursor object from a Bitmap object?

查看:304
本文介绍了如何创建从位图对象Cursor对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个现有的 System.Drawing.Bitmap 的对象,如何创建一个 System.Windows.Forms.Cursor 具有相同的像素数据作为我的位图对象的对象?

Assuming I have an existing System.Drawing.Bitmap object, how do I create a System.Windows.Forms.Cursor object with the same pixel data as my Bitmap object?

推荐答案

这个答案是从的这个问题。它可以让你无论从位图对象创建游标并设置其热点。

This answer is taken from this question. It allows you to both create a Cursor from a Bitmap object and set its hotspot.

public struct IconInfo
{
    public bool fIcon;
    public int xHotspot;
    public int yHotspot;
    public IntPtr hbmMask;
    public IntPtr hbmColor;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

/// <summary>
/// Create a cursor from a bitmap without resizing and with the specified
/// hot spot
/// </summary>
public static Cursor CreateCursorNoResize(Bitmap bmp, int xHotSpot, int yHotSpot)
{
    IntPtr ptr = bmp.GetHicon();
    IconInfo tmp = new IconInfo();
    GetIconInfo(ptr, ref tmp);
    tmp.xHotspot = xHotSpot;
    tmp.yHotspot = yHotSpot;
    tmp.fIcon = false;
    ptr = CreateIconIndirect(ref tmp);
    return new Cursor(ptr);
}


/// <summary>
/// Create a 32x32 cursor from a bitmap, with the hot spot in the middle
/// </summary>
public static Cursor CreateCursor(Bitmap bmp)
{
    int xHotSpot = 16;
    int yHotSpot = 16;

    IntPtr ptr = ((Bitmap)ResizeImage(bmp, 32, 32)).GetHicon();
    IconInfo tmp = new IconInfo();
    GetIconInfo(ptr, ref tmp);
    tmp.xHotspot = xHotSpot;
    tmp.yHotspot = yHotSpot;
    tmp.fIcon = false;
    ptr = CreateIconIndirect(ref tmp);
    return new Cursor(ptr);
}

这篇关于如何创建从位图对象Cursor对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆