Tuesday, October 13, 2009

Make the mouse wheel work properly in TListBox

Here is how to a make a descentant of a TListBox to behave properly when user tries to scroll using the mouse wheel.Instead of scrolling down to the bottom of the list
this code will make TListBox to scroll by one item at a time,regardless of the mouse wheel direction up or down.

unit sodListBox;
interface
uses
Classes
,StdCtrls
,Windows
,Messages
;
type
TsodListBox = class(TListBox)
private
{ Private declarations }
protected
{ Protected declarations }
procedure WndProc(var Message : TMessage);override;
public
{ Public declarations }
constructor Create(AOwner:TComponent);override;
destructor  Destroy;override;
published
{ Published declarations}
end;

implementation
{------------------------------------------------------------------------------}
constructor TsodListBox .Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
{------------------------------------------------------------------------------}
destructor TsodListBox .Destroy;
begin
inherited;
end;
{------------------------------------------------------------------------------}
procedure TsodListBox .WndProc(var Message: TMessage);
var
i : SmallInt;
begin
case Message.Msg of
WM_MOUSEWHEEL :
begin
//Changing the message code from mousewheel to keydown
Message.Msg    := WM_KEYDOWN;
Message.LParam := 0;
//Finding the direction of mousewheel up or down.
i              := HiWord(Message.WParam);
//Simulating a keystroke according to mousewheel direction.
if i > 0 then
Message.WParam := VK_UP
else
Message.WParam := VK_DOWN;
end;
end;
inherited WndProc(Message);
end;
{------------------------------------------------------------------------------}

There you go you now have a TListBox behaving properly to mousewheel.

1 comment:

Blogroll(General programming and Delphi feeds)