1. Computing

How to Convert a Bitmap to a Cursor

From , former About.com Guide

How to Convert a Bitmap to a Cursor

A cursor (mouse pointer) in Delphi applications is controled by the Cursors and Cursor property of the global Screen object.
Every Delphi control (visible component like TButton or TEdit) exposes the Cursor property that enables a developer to change the mouse pointer for the control using any of the predefined cursors provided by TScreen.

BMP to CUR

Let's say you have a bitmap (BMP) image you would like to convert to a cursor and use in your application. Here's what you need to do (backwards):
  1. Call the CreateIconIndirect Windows API function to create a cursor to be added to the Screen.Cursors property.
  2. The CreateIconIndirect function creates a cursor (or an icon) from a TIconInfo record.
  3. The TIconInfo takes two bitmap images to draw the cursor. One image is used as a mask and another for the cursor image.
  4. Use the TBitmap Delphi class to load a bitmap (two of them) and fill the IconInfo record.
  5. Finally: when you are finished using the cursor, destroy it using the DestroyIcon function.

An example of a custom image cursor...
Drop a TButton on a Form and handle the OnClick event of the button. Note: "Circle.BMP" and "CircleMask.BMP" are two bitmap images used to create a cursor.

Full source code below (or download):

~~~~~~~~~~~~~~~~~~~~~~~~~
...

interface

const
   crMyCursor = 1;
var
   iconInfo : TIconInfo;

implementation

procedure TForm1.Button1Click(Sender: TObject) ;
var
   bmpMask : TBitmap;
   bmpColor : TBitmap;
begin
   bmpMask := TBitmap.Create;
   bmpColor := TBitmap.Create;

   bmpMask.LoadFromFile('CircleMask.bmp') ;
   bmpColor.LoadFromFile('Circle.bmp') ;

   with iconInfo do
   begin
     fIcon := false;
     xHotspot := 15;
     yHotspot := 15;
     hbmMask := bmpMask.Handle;
     hbmColor := bmpColor.Handle;
   end;

   Screen.Cursors[crMyCursor] := CreateIconIndirect(iconInfo) ;

   Screen.Cursor := crMyCursor;

   bmpMask.Free;
   bmpColor.Free;
end;

procedure TForm1.FormDestroy(Sender: TObject) ;
begin
   DestroyIcon(Screen.Cursors[crMyCursor]) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to Detect the Start Move/Resize, Move and Stop Move/Resize events of a Form
« How to Convert an amount of Milliseconds to a TDateTime Value

©2013 About.com. All rights reserved.