Advanced Mouse Processing in Delphi Applications

Advanced Mouse Processing in Delphi Applications

You might already know how to handle some basic mouse events like MouseUp/MouseDown and MouseMove. However, there are times when you want your mouse to do what you tell it.

'Basic' API stuff

Many of us write programs that are designed to work only with the mouse. If we are writing programs that require mouse presence and/or are dependent on the mouse we have to be sure that various things are set up the right way.

Is Mouse Present?

The quickest way to see if the mouse is present:

Animated Mouse Cursor

Here's how to use animated cursors (or even how to use a BMP as a CUR):

Positioning the Mouse

The SetCursorPos API function moves the cursor to the specified screen coordinates. Since this function does not get a windows handle as a parameter, x/y have to be screen coordinates. Your component does use relative coordinates, e.g. relative to a TForm. You have to use the ClientToScreen function to calculate the proper screen coordinates.


On most occasions we want the mouse to move to a certain position on the screen. We know that some components do not respond to a cursor change until the user moves the mouse, we have to provide some small move-from-code technique. And what about simulation mouse clicks without calling the OnClick event handler?

The following example will simulate mouse click event on Button2 after the click to Button1. We have to use mouse_event() API call. The mouse_event function synthesizes mouse motion and button clicks. Mouse coordinates given are in "Mickeys", where there are 65535 "Mickeys" to a screen's width.

Restrict The Mouse Movement

Using the Windows API function ClipCursor, it is possible to restrict the movement of the mouse to a specific rectangular region on the screen:

Mouse Enter, Mouse Leave?

Detecting entering and exiting of the mouse pointer over a component is often coming up when writing your own component. All descendants of TComponent send a CM_MOUSEENTER and CM_MOUSELEAVE message when the mouse enters and leaves the bounds of the component. You will need to write a message handler for the respective messages if we wish to respond to them.