Question

dll mousehook or journaling thru my own application?

Asked by: urif

ok, at the moment i am creating a mouse journal (hook) because i need my application to know where is the mouse, if the mouse move, if the user pressed left, right or whatever mouse button, etc.
see the question after all the code

this is the code for the journaling:

function JournalProc(Code, wParam: Integer; var EventStrut: TEventMsg): Integer; stdcall;
var
  s: string;
begin
  {this is the JournalRecordProc}
  Result := CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut));
  if Code < 0 then Exit;

  {you should cancel operation if you get HC_SYSMODALON}
  if Code = HC_SYSMODALON then Exit;
  if Code = HC_ACTION then
  begin
    s := '';

    if EventStrut.message = WM_LBUTTONUP then
    begin
     if not form2.CheckBox1.Checked then //no stiky double-click
     begin
       doubleclick:=false;
       form1.SpeedButton1.Down:=true;
     end;
    end;

    if EventStrut.message = WM_LBUTTONDOWN then
    begin
      form1.TILed1.Flash;
      form1.TILed1.Caption:='L';
    end;

    if EventStrut.message = WM_RBUTTONDOWN then
    begin
      form1.TILed1.Flash;
      form1.TILed1.Caption:='R';
    end;

    if (EventStrut.message = WM_RBUTTONUP) then
    begin
        if not form2.CheckBox1.Checked then //no stiky righ-click
        begin
           leftclick:=true;
           form1.SpeedButton1.Down:=true;
        end;
    end;

    if (EventStrut.message = WM_MOUSEWHEEL) then
    begin
      //s := 'Mouse Wheel at X pos ' +
      //  IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);
    end;

    if (EventStrut.message = WM_MOUSEMOVE) then
    begin
      form1.MouseMoveReceived;
      posx:=EventStrut.paramL;
      posy:=EventStrut.paramH;
    end;

    if s <> '' then
    begin
       Form1.Label3.Caption:=s; //debug
    end;
  end;
end;


and i am starting the journaling with:

JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, hInstance, 0);

and stopping it with:

UnhookWindowsHookEx(JHook);

also, since the windows cancels the journal when the user presses ctrl-esc or ctrl-alt-del i am restarting it with:

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
  var Handled: Boolean);
begin

  Handled := False;
  if (Msg.message = WM_CANCELJOURNAL) and FHookStarted then
    JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, hInstance, 0);

end;

now, here's the problem. while the hook is on i experience the following:
the start menu and any of the sub-menues there will flicker, as if someone if repetedly moving the mouse of the items and reopening them. also alt-tab will show the task change little form but it will disappear almost intantly.
all this might be related to the journal, or maybe to the rest of my code, that simple clicks the mouse by code when the user moves and stops the mouse somewhere on the screen. in any case, what's better a mouse journal or a full dll hook on the mouse in this case?
the case beeing the ability to know where the mouse is at any given time, to know whether the mouse is moving or not, whether it;s a left click, right click, double click or the mouse is till down (the user is dragging the form, etc).

if a full dll is better, i know the journaling could be problematic - hence this entire question, does anyone has simple example for a mouse hook thru a dll?

thanks and sorry for the poor english.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-09-20 at 06:51:53ID21567608
Tags

hook

Topic

Delphi Programming

Participating Experts
2
Points
100
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. WM_CLOSE Event in a DLL
    IF I load a DLL with load library can I be able to map a WM_CLOSE from the DLL. Is there any way that can map the WM_CLOSE on the DLL. That, whenever the user end the task from the task manager the WM_CLOSE of the DLL is fired.
  2. Longint
    This one might be impossible because I mightn't be able to give you enough to go on. Just in case it's something obvious, here goes - I have transplanted a piece of code from one application to another and it doesn't work in the new app. A typed file has one element of it's...
  3. longint Character thingy...
    OK I asked a question yesterday which was answered perfectly, but I forgot one thing. it needs to recognize characters as well as numbers, you can see the action i want performed (line 151) but I get errors when compiling, do I need to write a new 'Procedure'(line 24) for inc...
  4. Main Menu WM
    I am making a mod for program and i want to add my own menu into a program but i dont want to edit the exe cause i want it to be a legal mod so is there a better way or how can i do this way of adding a menu into a program. What i am doing at the moment is i got the handle o...
  5. Detect user login (like WM_USERCHANGED)
    Hi Experts, I'm doing a Service and this NT-service is interacting with the desktop. I need to know when then user login to the system OR when the taskbar is created. I know that WM_USERCHANGED wont work on Win2000 or XP - so how do i trap system login ?? I have read a lot...
  6. Why can't I use IntToStr() in a Intraweb application?
    I try to use the function IntToStr() in IWunit1, but it shows the following errors: CountLabel.Caption := IntToStr(AvailableList.Items.Count) + ' available theatres.';//the line with error [Error] IWUnit1.pas(49): Undeclared identifier: 'IntToStr' [Fatal Error] IWProject.d...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: RadikalQ3Posted on 2005-09-20 at 07:21:39ID: 14920391

Hi!

Here you have a system mouse hook with DLL

In English:
http://www.q3.nu/trucomania/truco.cgi?414&ing

Also in Spanish:
http://www.q3.nu/trucomania/truco.cgi?414&esp

(I dont know what is your languaje) :)

 

by: urifPosted on 2005-09-20 at 07:44:25ID: 14920625

it's actually both languages :)

anyway, the code seems to work fine under winxp, although a lot of posts in the link you send me tell that it doesn't work on xp or 2000. let me play with it for a bit.
 now what do you suggest, a full dll hook or a far simpler journaling?

 

by: RadikalQ3Posted on 2005-09-20 at 08:11:42ID: 14920847

The posts related badfunction are old...
The first version if that tip was written for Win98.
In win2k/xp, the DLL name (in the declaration) must have the extension and this is the cause for that posts.
The hook works in Win98/2k/xp without problems.

>a full dll hook or a far simpler journaling?

A Global hook must be in a DLL, even a journal hook.
There are two kinds of hook that works without DLL:

Low level Mouse Hook (constant WH_MOUSE_LL) and Low level Keyboard Hook (WH_KEYBOARD_LL)

 

by: RadikalQ3Posted on 2005-09-20 at 08:13:11ID: 14920864

Huff i press enter...

The rest of the hooks must reside in a DLL (if you want a global system hook) or... you will have extrange efects :)

 

by: urifPosted on 2005-09-20 at 11:41:02ID: 14922828

ok, the example as it is on the link you sent me works ok, the thing is that when i added a bit of code so it will change a few variables when the program clicks the mouse then the whole thing goes nuts.
1st, it's not detecting leftmouse up, only down so when i send a mouse up by code and the dll is not detecting it then the variables are not getting updated. i can;t seem to be able to find why, by the way the same happens when i manually press the left button, it will detect down but not up.
2nd as soon as the form is refreshed or repainted (for exaple when you set it to ontop=true or when you restore it from the tray) then the hook doesn;'t work anymore, at all. my guess is that i need to stop the hook and restart it again.

 

by: Slick812Posted on 2005-09-20 at 14:42:25ID: 14924290

hello  urif , , The Journal Hook will merge the input queues of the programs, this is not noticible most of the time , but can cause some abnormallities (unusuall things, sometimes in text entry). . . I Used to recommend using the Journal hook, , but now I recommend to ONLY use the journal hook to Record and play back key amd mouse, for a short time, , , in any other mouse or key monitor, you should use a WH_MOUSE hook, or th key hook. . . .

below is some code for a mouse hook, that is in a DLL library, It does not do any of the things that you describe in your comment above, It seems to work for me - -


library GetMouseMove;

uses
  Windows, Messages;

{$R *.RES}

const
MoveMsg: Integer = WM_USER + 814;
UpMsg: Integer = WM_USER + 815;
WheelMsg = WM_USER + 816;
mapName = 'h7y+u2a5pe'; // be sure to change this to you own UNIQUE map file name

var
pForm: PDWORD = nil;
hForm: THandle = 0;
hMemFile: THandle = 0;
hHook: THandle = 0;
Hooked: Boolean = False;

function HookProc(Code, wParam: Integer; var MouseStrut: TMOUSEHOOKSTRUCT): Integer; stdcall;
begin
Result := CallNextHookEx(0, Code, wParam, Integer(@MouseStrut));
if (hForm <> 0) and (Code = HC_ACTION) then
  if (wParam = WM_MOUSEMOVE) then
    begin
    ScreenToClient(MouseStrut.hwnd, MouseStrut.pt);
    PostMessage(hForm, MoveMsg,MouseStrut.pt.x, MouseStrut.pt.y);
    end else
    if (wParam = WM_LBUTTONUP) then
    PostMessage(hForm, UpMsg,0, 0) else
    if (wParam = WM_MOUSEWHEEL) then
    PostMessage(hForm, WheelMsg,MouseStrut.dwExtraInfo, 0);
end;


function StartHook(formHnd: HWND) : Boolean; export;
begin
Result := False;
if Hooked then
  begin
  Result := True;
  Exit;
  end;

if not IsWindow(formHnd) then Exit;

hHook := SetWindowsHookEx(WH_MOUSE, @HookProc, hInstance, 0);
if hHook <> 0 then
  begin
  hMemFile := CreateFileMapping($FFFFFFFF, nil,PAGE_READWRITE,0,
              SizeOf(Integer), mapName);
  pForm := MapViewOfFile(hMemFile, FILE_MAP_WRITE, 0, 0, 0);
  if pForm = nil then
    begin
    CloseHandle(hMemFile);
    UnhookWindowsHookEx(hHook);
    end else
    begin
    hForm := formHnd;
    pForm^ := formHnd;
    Hooked := True;
    Result := True;
    end;
  end;
end;

function StopHook: Boolean; export;
begin
if pForm <> nil then
  begin
  UnmapViewOfFile(pForm);
  CloseHandle(hMemFile);
  pForm := nil;
  hForm := 0;
  end;
if Hooked then
  Result := UnhookWindowsHookEx(hHook) else
  Result := True;
if not Result then Exit;
Hooked := False;
hHook := 0;
end;

procedure StartUp;
begin
hMemFile := OpenFileMapping(FILE_MAP_WRITE, False, mapName);
if hMemFile <> 0 then
  pForm := MapViewOfFile(hMemFile, FILE_MAP_WRITE, 0, 0, 0);
if pForm <> nil then
  hForm := pForm^;
end;

procedure EntryProc(dwReason : DWORD);
begin
if (dwReason = Dll_Process_Detach) then
  begin
  if Hooked then UnhookWindowsHookEx(hHook);
  if pForm <> nil then
    UnmapViewOfFile(pForm);
  pForm := nil;
  CloseHandle(hMemFile);
  hMemfile := 0;
  end;
end;

exports
  StartHook,
  StopHook;

begin
StartUp;
DLLProc := @EntryProc;
end.

 

by: Slick812Posted on 2005-09-20 at 14:49:27ID: 14924330

some code in the Form1 -


  private
    { Private declarations }
    MouseTravel: Int64;
    MouseClick: Int64;
    WheelTurn: Int64;
    MousePos: TPoint;
    procedure MoveMsg(var Message: TMessage); message WM_USER + 814;
    procedure UpMsg(var Message: TMessage); message WM_USER + 815;
    procedure WheelMsg(var Message: TMessage); message WM_USER + 816;



procedure TForm1.MoveMsg(var Message: TMessage);
begin
if MousePos.x <> -200000 then
MouseTravel := MouseTravel+ Round(Sqrt(SumOfSquares([abs(Message.LParam-MousePos.y),
      abs(Message.WParam-MousePos.x)])));

MousePos.x := Message.WParam;
MousePos.y := Message.LParam;
Label5.Caption := IntToStr(MouseTravel);
end;

procedure TForm1.UpMsg(var Message: TMessage);
begin
Inc(MouseClick);
Label6.Caption := 'Clicks '+IntToStr(MouseClick);
end;

procedure TForm1.WheelMsg(var Message: TMessage);
begin
Inc(WheelTurn, (Message.WParam div 300000000));
Label7.Caption := 'Wheel '+IntToStr(WheelTurn);
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
MousePos.x := -200000;
MouseTravel := 0;
MouseClick:=0;
WheelTurn:=0;
end;


procedure TForm1.sbut_MouseMoveHookClick(Sender: TObject);
var
hLibMM: THandle;
StartHook1: function(formHnd: THandle): Boolean;
begin
hLibMM := LoadLibrary('GetMouseMove.dll');
if hLibMM = 0 then
  begin
  Showmessage('ERROR - DLL did NOT load');
  Exit;
  end;
@StartHook1 := GetProcAddress(hLibMM, 'StartHook');
if @StartHook1 = nil then
  begin
  Showmessage('ERROR - StartHook1 is NIL');
  Exit;
  end;
if not StartHook1(Handle) then
  begin
  Showmessage('ERROR - Mouse Hook is Not Started');
  FreeLibrary(hLibMM);
  end;
end;

 

by: Slick812Posted on 2005-09-20 at 14:53:47ID: 14924348

and I will add that a DLL is loaded into every running process, that has a window in the system Message queue, so  variables in one your DLLs will NOT be set from a DLL in a diffent process, if you need any Global DLL variables, you will need to add them to the Map File,

 

by: urifPosted on 2005-09-21 at 00:29:24ID: 14926256

ok, out of the box it seems to work, the problem here is that the function

function HookProc(Code, wParam: Integer; var MouseStrut: TMOUSEHOOKSTRUCT): Integer; stdcall;
begin
Result := CallNextHookEx(0, Code, wParam, Integer(@MouseStrut));
if (hForm <> 0) and (Code = HC_ACTION) then
  if (wParam = WM_MOUSEMOVE) then
    begin
    ScreenToClient(MouseStrut.hwnd, MouseStrut.pt);
    PostMessage(hForm, MoveMsg,MouseStrut.pt.x, MouseStrut.pt.y);
    end else
    if (wParam = WM_LBUTTONUP) then
    PostMessage(hForm, UpMsg,0, 0) else
    if (wParam = WM_MOUSEWHEEL) then
    PostMessage(hForm, WheelMsg,MouseStrut.dwExtraInfo, 0);
end;

gets me some errors whenever i try to add some other wParams to watch.
as i said, i need to monitor(see the journal i created) leftmousedown and up, rightmousedown and up, doubleclick, mousemove and if mouse is over the caption area.
trying to customize the dll to be a general hook is not that easy as it seems.

 

by: urifPosted on 2005-09-22 at 09:47:15ID: 14938267

after some long debuggin the solution presented by RadikalQ3 was the closes to what i was looking for, so the points go to him.
thanks so much for the help
you can see the working code on geocities.com/uf_new

i'd like to add you on the acknowledgements

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...