Mega Code Archive

 
Categories / Delphi / Graphic
 

How to Convert a Bitmap to a Cursor using Delphi code

Title: How to Convert a Bitmap to a Cursor using Delphi code 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): Call the CreateIconIndirect Windows API function to create a cursor to be added to the Screen.Cursors property. The CreateIconIndirect function creates a cursor (or an icon) from a TIconInfo record. The TIconInfo takes two bitmap images to draw the cursor. One image is used as a mask and another for the cursor image. Use the TBitmap Delphi class to load a bitmap (two of them) and fill the IconInfo record. 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; ~~~~~~~~~~~~~~~~~~~~~~~~~