Accueil > code > Hardware cursor in OpenGL

Hardware cursor in OpenGL

In my current game Dungeon Eye, I need to have a custom cursor. My first approach was to hide the system cursor and in every frame, draws my custom cursor at the mouse location. It’s quite easy but not perfect. You have some slowdowns as a side effect. Not perfect…

The solution is to have custom cursor. All that you have is an image of your cursor and the following code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/// <summary>
/// Creates a new hardware cursor
/// </summary>
/// <param name="bmp">Bitmap handle</param>
/// <param name="hotspot">Cursor hotspot</param>
/// <return>A Cursor handle</return>
static public Cursor HardwareCursor(Bitmap bmp, Point hotspot)
{
	User32.IconInfo tmp = new User32.IconInfo();
	User32.GetIconInfo(bmp.GetHicon(), ref tmp);
	tmp.xHotspot = hotspot.X;
	tmp.yHotspot = hotspot.Y;
	tmp.fIcon = false;
 
	return new Cursor(User32.CreateIconIndirect(ref tmp));
}

And now here’s the Platform Invocation Services :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 /// <summary>
/// 
/// </summary>
/// <param name="hIcon"></param>
/// <param name="pIconInfo"></param>
/// <returns></returns>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
 
/// <summary>
/// IconInfo
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct IconInfo
{
    /// <summary>
    /// Specifies whether this structure defines an icon or a cursor.
    /// A value of TRUE specifies an icon; FALSE specifies a cursor
    /// </summary>
    public bool fIcon;
 
    /// <summary>
    /// The x-coordinate of a cursor's hot spot
    /// </summary>
    public Int32 xHotspot;
 
    /// <summary>
    /// The y-coordinate of a cursor's hot spot
    /// </summary>
    public Int32 yHotspot;
 
    /// <summary>
    /// The icon bitmask bitmap
    /// </summary>
    public IntPtr hbmMask;
 
    /// <summary>
    /// A handle to the icon color bitmap.
    /// </summary>
    public IntPtr hbmColor;
}
 
/// <summary>
/// CreateIconIndirect
/// </summary>
/// <param name="icon"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

To use the new cursor, simply set the Cursor property of your Form with the created hardware cursor. It’s also possible with a little effort to use OpenGL texture (or sub part of it) as HardwareCursor.

For more informations, look at my HardwareCursor class.

  1. Pas encore de commentaire
  1. Pas encore de trackbacks
Vous devez être identifié pour poster un commentaire