Back


Lennie's Weekly Tip : Detecting your Mouse

18 October 1999 Ref. 01



Sometimes a programmer will want to know, whether the user has a Mouse-device installed on his system and how many buttons the Mouse has.

Look at the following two Delphi-functions :

function MouseExist : boolean;
begin
  if (GetSystemMetrics(SM_MOUSEPRESENT) <> 0) then
    Result := True
else
   Result := False;
end; {MouseExist}

Remarks :
This function will check if a Mouse-device is installed on the user's system, it will return TRUE if one is present or FALSE, otherwise.

function MouseButtonsCount : integer;
begin
    Result := GetSystemMetrics(SM_CMOUSEBUTTONS);
end; {MouseButtonsCount}

Remarks :
This function will return the amount of buttons available on the Mouse-device. If no mouse is available it will return a value of 0.

Remember to add the "ShellAPI" unit to you application's uses-clause.

Test Example :

To test these function,

1. Add a button(TButton) and a label(TLabel) to the main form (TForm), double-click on the button and add the following code to it's "OnClick" event-handler.

begin
  if (MouseExist) then
    Label1.Caption := 'Mouse-device installed, with ' + IntToStr(MouseButtonsCount) + ' buttons avialible...'
else
  Label1.Caption := 'No Mouse-device installed...';
end;

2. Run the application (pressing F9) and click on the button. The label will then respond with a message that a Mouse-device is installed and how many buttons it has OR if no Mouse-device is installed.

My Test-Results :

When I tested these function, the label responded with a message, that the mouse is present and that it has 2 buttons (totaly right). When I continued and un-plugged the Mouse from my computer, it responded with a message that no Mouse-device are installed.

If you don't believe me (you will...) then try the test yourself, you'll be surprised :-)


Back