Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

[solved] How To Do Global Mouse Hook In VB .NET?

Looks like .NET does not support global system hook. I got an example of system wide disable mouse:, it works in XP Pro. However, if I only disable some of the mouse event, i.e. LButtomUp and LButtonDown only, then sometimes I got error. What's the difference between disable all mouse events and some of them? Anyone has a better way to do this in VB .NET?

I'm doing a program in VB6 which runs great, however, I want to change it to VB .NET, then I found MS VB .NET does not support global mouse hook, what should I do now? Stay at VB6?


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Global Hook
Hi All,

How can I return the selected (highlighted) word/text from any given application?

Eg. I select a word in Excel (or Outlook, Access, Visio etc) and upon a click of a Button, I MsgBox the word.

I'm gussing a global (system wide) hook of some kind.


Trying To Get A Global Hook From VC++ Dll To VB
The VC++ dll code looks like this

#include <windows.h>

#pragma data_seg(".shared")

// This section contains all data necessary for hook function. This section
// is shared between all applications, as the hook function can be called
// in the context of any application. Note, that all data in this section
// must be explicitly initialized, otherwise they will be placed in the .bss
// section */


#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")

HINSTANCE g_hInstance;

LRESULT CALLBACK CheckKey (int nCode, WPARAM wParam, LPARAM lParam);
extern "C"

if (uReason == DLL_PROCESS_ATTACH)
g_hInstance = hInst;

return TRUE;

long _stdcall SetHook(HWND hWnd)

g_hWnd = hWnd;
g_hHook = SetWindowsHookEx(WH_KEYBOARD,CheckKey, g_hInstance, 0);
return ((LONG)g_hHook);

long _stdcall RemoveHook(void)
return (LONG)UnhookWindowsHookEx(g_hHook);

LRESULT CALLBACK _stdcall CheckKey (int nCode, WPARAM wParam, LPARAM lParam)
if (nCode < 0)
// Immediately call next hook as documentation states
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
if (lParam<0)
if (((wParam>45) && (wParam<91)) || (wParam==32) )//This part captures only the following keystokes a-z ,0-9 and the space key
PostMessage(g_hWnd, M_KEYDOWN, wParam, lParam);
PostMessage(g_hWnd, WM_KEYUP, wParam, lParam);

return CallNextHookEx(g_hHook, nCode, wParam, lParam);

in VB I call sethook at it works no problem. However I was wondering how do I get the messages in VB?

Basically I am trying to make a global keyboard hook using a VC++ DLL.

Global Keyboard Hook How To ?
I want to create a program to start runing when windows starts. This program must intercept all keystrokes in order to append them to a disk file. How can this be done ? I know how to do a keyboard hook, but, inside a particular program. Now, I want to have it in a global mode !

Thanks in advance !

Global Hook Problem
well i wrote this dll in c++ that has a function that sets the hook and the hook procedure. my vb program calls sethook with its own handle and the dll is supposed to set the hook (which it does) and returns the hook handle but when the conditions are met in the hook procedure it seems to only work for my vb process and it only works once. to make it easier i have a mouse hook which looks for right clicks on the title bar. i can right click on my apps title bar and it works the first time but if i do it again it doesn't work as well as not working for other processes. my dll has the a shared area for the hook handle and my apps handle set up w/ the #pragma and my .def file has everything declared correctly. any ideas would be helpful.

DLL And Global Hook Questions
I have a few questions about Hook functions and DLLs. I want to write a global hook function and from what I understand it has to reside in a DLL. I wrote a Low Level Keyboard hook and the function resides in my VB code and seems to work just fine. However, when I tried load up my debug hook code, it locked up my PC. So Iím thinking while my VB keyboard hook code may work, it may fail at a later date. Because of this, I need to move it to a DLL.

If you are going to call a function the resides inside of a DLL, do you have to load that DLL first using load library if no other Exe is using it?

If you have a DLL that has a global hook function, can you call a different function inside of the same DLL from VB that will register that hook? Also, is there some type of main function that always gets executed when a DLL loads such that it could automatically register that global hook?

Can you call a function inside of a DLL and have it load another DLL?

If several executables reference the same DLL, is there anyway to determine which instance of a DLL you are working with or does each executable get itís own copy of a DLL when ever it calls one of a DLLs functions?

Runtime Error 91. [Solved], ADO Global Connect [Not Solved]
I am sure this problem has to do with further lack of my knowledge of modules. But here is what is happening.

If you remember from my last post, I have a module now named Uconnect. Here is the code in thre:

VB Code:
Public Conn As ADODB.Connection  Public Sub UserConnect()Set Conn = New ADODB.ConnectionConn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};" _& "SERVER=;" _& "DATABASE=testim;" _& "UID=" & Form1.txtUser.Text & ";" _& "PWD=" & Form1.txtPass.Text & ";" _& "OPTION=" & 1 + 2 + 8 + 32 + 2048 + 16384 Conn.CursorLocation = adUseClientConn.OpenDebug.Print Conn.State End Sub

That all works great now when I call the Sub from my main form. Connection state shows a 1. Here is the problem. Right after I call this sub from the main form, I have an If Else statement checking to see if the connection is good.

VB Code:
Call UserConnectIf Conn.State = 1 Then Unload frmInfo Form1.Caption = "You are logged " Set rs = New ADODB.Recordset Etc, Etc, Etc.

On debugging, as soon as the Call to UserConnect is done I get this error on the If Conn.State =1 Then line.

RunTime Error 91
Object Variable or With block variable not set.

As usual, I am sure I am missing something simple.

Thanks again

Mouse Hook
For practice, I set up a thread-specific, local mouse hook on my Visual Basic application.

The problem is that the hit test always a 0 for the area of the screen where the mouse is currently located. And the Window class also retrieves a null string all the time.

Can someone point out the cause of the problem? Here's the code snippet.

Mouse Hook-I Think
As i posted before in another post I need a program which does the following thing:
Once I highlight a text with the mouse in a window program, mainly the browser and then press ctrl+c the highlighted text will be transfered into a text box (multilined) in my form.
Thanks in advance.

Mouse Hook-I Think
As i posted before in another post I need a program which does the following thing:
Once I highlight a text with the mouse in a window program, mainly the browser and then press ctrl+c the highlighted text will be transfered into a text box (multilined) in my form.
Thanks in advance.

Mouse Hook
For practice, I set up a thread-specific, local mouse hook on my Visual Basic application.

The problem is that the hit test always a 0 for the area of the screen where the mouse is currently located. And the Window class also retrieves a null string all the time.

Can someone point out the cause of the problem? Here's the code snippet.

Keyboard And Mouse Hook
Using SetwindowsHook apifunction, i cannot hook both keyboard and Mouse.
Whenever i use both hooks the application gets closed.
Is there any way for using both Keyboard and Mouse hook.

Windows Mouse Hook Failing
I have a piece of code which implements a windows hook on mouse functions which works fine. It displays the current position, and can detect button up and down messages. I use the standard SetWindowsHook, CopyMemory, CallNextHookEx commands like on other topics on this site.

However, when i move my mouse over the task bar in windows (i have it to auto hide), once the task bar pops up, my program no longer recieves any events or messages in the hook.

Has anyone had this problem before, or can anyone give me any guidance on where to look now. Searches on google and here has returned few results!

Im trying to emulate a tap and hold feature, which is found on most pocket pcs (e.g. tap on the screen, hold for a couple of seconds, and it does a right mouse click, and shows a context menu), since i have a graphics tablet.

My aim is to start a timer when the mouse button is pressed, then wait until the delay is greater than 2000 milliseconds, and send a right mouse button click (which ill have to look up) to the point on the window where the mouse currently is.

Thanks in Advance

Event Not Triggering From ActiveX EXE While Mouse Hook Is Set

I created an ActiveX EXE which includes xTimer so I can run some things asynchronously... What I want to do with it is to set a mouse hook in there and then raise an event when it detects a single or double click anywhere on the screen...

I have tested the code in an ordinary project and it works perfectly, however in this ActiveX EXE the events, which I raise when mouse click is detected, do not fire... I tried debugging it and the "RaiseEvent MyEvent" statement DOES execute, however I don't receive anything in calling program...

Even more strange is that events work before mouse is hooked and after it's unhooked.... It looks like it has a problem executing it when it's in LowLevelMouseProc procedure...

Also, I'm using mouse hooking, because I want to have complete control of the mouse, which means that other applications should not receive click events during that time

I'm attaching the sample project...

Any ideas?


How To Pass Information From Mouse Hook Proc To App?

I am trying to write a VB 6 program that displays the current mouse cursor position in a form, even when the mouse is outside of my window.
In order to do this, I think the only way is to implement a sytem mouse hook in a standard DLL (which must be written in C++, but well, I'll figure it out).

Q: How can I pass info from the mouse hook proc (which is in the C++ DLL) to my VB app? When the hook gets called, it must somehow notify my app about the event and update the cursor position.

Thanks for any help! This seems to be a tough one ...

Mouse Hook Not Working After Windows Lost Focus.
I'm using mouse hook to detect if user is using the mouse, hence checking if my program is being used or just idle.

I put a timer that counts down 900 seconds, program would auto logout if the timer reaches 0, and whenever a mouse click is hooked it'll reset the timer to 900.

It works quite well, but if I switch to another window, click something, and then switch back to my program, the mouse hook doesn't work (not catching any mouse click event) anymore.

Would someone please tell me what's wrong with my code and how should I fix this problem? Thanks a lot!!

The code is very simple, there's a form that calls EnableHooks() on load and FreeHooks() when unload:

Public Const WH_MOUSE As Integer = 7
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_RBUTTONDOWN = &H204
Public Const HC_ACTION = 0
Public TimeOutCounter As Long

Public Type POINTAPI
X As Long
Y As Long
End Type

Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpFn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, ByVal lpvSource As Long, ByVal cbCopy As Long)
Declare Function ScreenToClient Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long

Public hHook As Long ' handle of Hook Procedure

Sub EnableHooks()
If hHook = 0 Then
hHook = SetWindowsHookEx(WH_MOUSE, AddressOf MouseHookProc, App.hInstance, 0)
End If
End Sub

Sub FreeHooks()
Dim ret As Long
If hHook <> 0 Then
ret = UnhookWindowsHookEx(hHook)
hHook = 0
End If
End Sub

Function MouseHookProc(ByVal code As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If code < 0 Then
MouseHookProc = CallNextHookEx(hHook, code, wParam, lParam)
Exit Function
End If
TimeOutCounter = 900
End If
MouseHookProc = 0
Call CallNextHookEx(hHook, code, wParam, lParam)
End Function

Global Arrays [solved]
I am trying to send data from an array created in a sub in a module back to the calling procedure.

I can do this with variables by declaring the variable to be either public or global in the general decs section of the module.

However when i try the same thing with an array it recognises the array in the calling procedure but the contents of the array are empty.

Am I doing something wrong. Help appreciated.


Global Flag?***SOLVED*****
Hi, Happy New year to you all.

I have three forms.

Form one at the press of a button will envoke form two. If an option is selected on this form when the first button on form one is pressed for a second time form three is shown.

So what I want is a Global flag which I can set with one form and then check with another and perform something different if set.

Also, is there a way of displaying a form within a form and locking the focus to it? ie if I try to click on the form behind it wont let you?


Global Key Capture (not Outside Program) #SOLVED#

I have an MDI form with multiple other forms. I want to create Help messages for those forms.
My goal is to create a global key capture wich will only capture keys from my own program and then run some functions etc.

I've seen some exaples, but theire all not what I am looking for. I do not want to create a menu with a key shortcut (because I do not want menu's in those forms), I do not want to use the keydown event (because that would be a hell declarating) and I do not want to use that key capure example wich captures all keys with its timer (because it caputures outside my program).

Is there anything left for me to use?

Edited by - helemaalgeennut3 on 4/19/2004 7:18:38 AM

Global Arrays From A Module To Multiple Forms [solved]
Hey everyone, first post but Ive been to this site a few times before.
A guy who goes by the name of chemicalNova showed me, thanks.

But i have a problem with a school assessment of mine.
I have 3 forms, 1 is a menu to two others, the first is an input form and the second is an output form.
I have to assign everything that has been added to arrays, so there are multiple text boxes and combo boxes. Then be able to display, say a total of something that i have entered.
I am unsure of the syntax that is need to do this. I know i have to use a module and that is all.

Any help would be greatly appreciated.
Thanks, Mitch.

Global Mouse Position
Can anyone tell me how to get the mouse position from anywhere on the screen?

Change Global Mouse Apperance
I've put my App in the systray-section waiting for some events.
If there is an event I want to change the mousepointer to an animated
pointer from my own ani-file and restore it after a while.
The mousepoiter is NOT on a form in MyApp so I think I have
to change the "Screen.Mousepointer".



Capturing Global ButtonClicks For Hourglass Mouse
I'm looking for ideas more than help. I have an application with over 20 forms. It has only now just occured to me that whenever a button is clicked I would like the mouse icon to become the hourglass icon, until the code from the button click is complete, then the icon can return to the arrow icon. Right now, the only thing I can think of is to insert Screen.mousepointer= x lines at the start and end of EVERY button click. This would be very time consuming, so I'm hoping that there may be a way to just write one function that will capture all button clicks. I'm not sure if there is an API command for doing this or not, but it will be tricky since I want to capture both the start of the button click event, aswell as the termination of the button click event. Does anyone have any ideas ?

System Wide Hook To Capture Window Hook Creation On XP
I have a following code:

dim uRegMsg as long
dim OldProc as long

uRegMsg = RegisterWindowMessage(ByVal "SHELLHOOK")
OldProc = GetWindowLong(hWnd, GWL_WNDPROC)
SetWindowLong hWnd, GWL_WNDPROC, AddressOf WndProc

It works perfectly fine on NT and Win2K but not on XP. As soon as a window is created, my WndProc function is called. but not on XP.

Does the GetWindowLong and SetWindowLong need to be changed to
GetWindowLongPtr and SetWindowLongPtr, if yes can someone please
give me the function declaration of those functions and changes
in the code.I tried but does not quite work for me. If not then
please let me know if any suggestion you have.


Get Mouse Position [Solved]
How do I get the position of the mouse on the whole screen.

Mouse Event (solved)
Hi, I would like to know how to detect the left mouse click whether the form is focused or not. I want it to trigger commands as long as the mouse click is down. This is VB6.

SOLVED: Mouse Coordinates?
Hello, I'm trying to make a line follow the mouse movements, but I can't figure out how to do it in VB, could anyone please help me? I have a timer that has 1 interval that controls the y1/2 coords of the line, but i cant figure out how to make the coordinates of the y1/y2 follow the coords of the mouse...please help

Edited by - Dieten on 5/18/2005 12:16:19 PM

Directinput Mouse Input [solved]
what Im trying to do is make my own keylogger which globally records all keys / mouse clicks. (count only)
when it comes to keyboard im fine thats all good. The mouse I can do as well except when any directx game or opengl game is run the mouse will not register, not only that it makes the mouse impossible to use. meaning the cursor moves to the top of the screen and stays there. if I turn the mouse hook off it works fine , recording keyboard presses still. Ive tried different methods of capturing mouse even merrions eventvb dll and hotkey to no avail. Is there a way to do this, I only have vb5 and 6 , no c++(not that i can program in c++ anyway).

If someone could be so nice to suggest how I would get mouse clicks... I dont even need to know which button was clicked, its just making a counter increment by 1 every click.

a dll and how I would implement it would be appreciated or a snippet of vb code.

yes I have searched the forums for hooks etc and tried examples but none record thru ogl or dX, Ive even reverted to google

Thanx in advance if anyone can help.

Mouse Event Click &lt;solved&gt;
Hey, i was wondering how i could simulate a mouse click at a certain location on the screen. If anyone has any ideas on how to do this please respond.


Edited by - crazyoldman on 1/14/2006 5:03:32 PM

I'm Having Problems Detecting Mouse Clicks By Myself... [SOLVED]
I'm trying to have a popup menu display when the right mouse button is clicked inside a treeview. This would normally be simple using the MouseDown event, but I need to use the NodeClick event, and as you know, the NodeClick event doesn't use a Button variable, unless I add one myself.

I know this has to do with subclassing, but that's my weakest area. How would you subclass something like this?

How To Make A Global Connections And A Global Conditions???
Hi All!!

I have codes to start a connections to server database like this:

Option Explicit
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset

Private Sub Form_Load()
    Set con = New ADODB.Connection
    con.ConnectionString = "Provider=MSDASQL;dsn=MySQLDATA;uid=root;pwd=pass;database=biodata;"
    Set rs = New ADODB.Recordset
    rs.CursorLocation = adUseClient
    rs.Open "select * from biodata", con, adOpenStatic, adLockOptimistic
End Sub

The problem is this connections only work for form1.
I have five forms with actually need the same connection, the same open recordset, and
the same condition at the same time.

How to do that??
How to make a global connections or global conditions for all forms I've made??

Please anyone give me a sample codes.

Thank's always.

Global Variables Nott Global?
I have a Module that declares several arrays as public, some string, some
integers. I then have 2 forms. Form A is the main form, that loads on
start-up, and has a command button to open Form B. On form B there are
several text boxes where the array values can be changed, however when I
close B and go back to A, those values are lost. I thought Public meant

Larry L

Object Global Or Not Global
in one of my apps I use ADO a lot. now since there are many many users that connect to the same database to change data.. I only open/close recordsets as needed to pull data into a form or save it back to the database.. i never leave a connection/recordset open..

now my question is, should I make a public variable in my module for the ado connection and recordset? or dim them in the general declaration of each form that uses ADO in it?

There is never more than 1 recordset/connection open at a time as well...

Simple Question Solved, One More Thing Please. Solved
I am using VBA in Excel.

I want to save the excel sheet as a .txt file delimited by a pipe and overwrite it without that pop-up you get with that warning that you are overwriting an existing file.

Any quick help would make my day!

Edited by - jonnie on 10/6/2003 4:58:13 PM

Api Hook
Hello All,

I'm want to write a plugin for my application that can watch an installation for registry entries created, files created, and files copied. Also, i need to watch the installed program for the same stuff. The end goal here is to be able to repack the installation so that it can be deployed later. I've been creating a bootloader with some recover utilities in assembly for (NT 9X Linux). So, everytime i think it's ready, I get brave move it from the test computer to my good one....and a few days later......OOOPS...Reformat!!! I keep ghost backups now so it's not really a problem.. But i told myself I would write this so i'm going to give it a shot!!

So, how do i hook the api calls in a process so that i can log them?

Thanks very much for past and future responses!

How To Use A Hook ?

i want to take over a program for a period of time, to set settings right, but i don't want to let the mouse move and the program doesn't have to be the active window.

So i've heard that i need to use a hook, intercept the messages from the message pump, ignore those (to disable manual input), and put my own message in that program its message pump.

Now can someone give me a general idea how to use such a hook?
I know all the hooks for windows in vb can't go out of the process that creates it, but i just saw there is 1 that can, the Windows Journal PlayBack Hook.

Can anyone help me with that? All i want to do is send messages to the program to alter the options.

Thanks in advance

I am Using Hook and unHook to avoid right click and paste on my controls especially the password textbox.
This is leading to lot of memory VB Application keeps closing....
once i comment the code it does not close...
i dont have this problem in the Exe ??????

Any ideas why ???

Public Sub Hook(hwnd As Long)
lngHWnd = hwnd
lpPrevWndProc = SetWindowLong(lngHWnd, GWL_WNDPROC, _
AddressOf WindowProc)
End Sub

Public Sub UnHook()
Dim lngReturnValue As Long
lngReturnValue = SetWindowLong(lngHWnd, GWL_WNDPROC, lpPrevWndProc)
End Sub

Hook Into IE
how can you hook into an active IE window's textfield and get the text in it?


How To Hook?
im trying to send data from a file to a game called Diablo 2 in the data will be the persons account and password all i really want it to do is login with those txts

API Hook
How would you API Hook WriteProcessMemory on another process?

I have a vague idea but not clear enough for me to overcome.

Hook Help
Ok, so I have the hook in place and it works, but there is a slight problem. I have it so it will send all the keys to a text box, however, upon hitting a single key one time it returns the letter several times.

Does anyone know of a way I could trap it so it will only return it once?

I have a problem with a hook:
hHook = SetWindowsHookEx(WH_KEYBOARD, AddressOf KeyboardProc, App.hInstance, App.ThreadID)

and in Form_Unload:
UnhookWindowsHookEx hHook

After the program ends the VB crashes...
What's the problem?

DLL Hook
Ok I Am Lookin To Make A DLL Hook Is There A Source Code.Theres A Program That Reads Memory And I want To Unhook It And Hook My Own To Read What I Want i Heard LoadLibraryA If Anyone Give Me A Hand With This I Would Appreciate It Thx

IE Hook
Two-fold Q here:
1.) I am looking to create an IE toolbar/toolbar button for my app.
2.) This app needs to intercept the BeforeNavigate2 Event in IE.

How do i create the button?

And How do i intercept the event

**Bonus** Can anyone do it for netscape too?

Hook Does Not Hook?
Aaron Young's hook program works well on my pc but when i try it on the workstation of my university LAN it doesnot even hook. it just ends after specifying the path of the file to store the logs.

Is there a solution to the problem?

CBT Hook
I am trying to create an program that will hook whenever a new window is opened and be able to tell me the EXE from that windows process. I can do the second part just fine but I'm having trouble with The CBT Hook.

I can't get the hook to be global, it only tells me when windows are opened in my process. Does anyone know how I can make a Global CBT hook, If I can make a global CBT Hook?

I was reading the documentation from msdn on SetWindowsHookEX and it would appear that a CBT Hook can be global unless global means something that I don't think it does. Right now I'm using the hook library availiable on VbAccelerator

Edited by - msg555 on 1/1/2005 11:59:57 AM

Solved - How To Close Solved Threads?
I am a new member to this forum.
can somebody tell me how to close solved threads.
I have created 2 threads and which are solved. I would like to close them.

[SOLVED] Wierd Saving Bug [SOLVED]
i am using this code to save some settings to a file

VB Code:
Public Sub saveini(filename As String)If Replace(filename, " ", "") = "" Then filename = "default.ini"  Open (filename) For Output As #1   Print #1, "[Ump3 V2 ini file]"   Print #1, "Groups{" & playlistsettings.GROUPS   Print #1, "Playlist{" & playlistsettings.file   Print #1, "Skin=default"   Print #1, "randomize{" & playback.randomized   Print #1, "repeat{" & playback.repeat  Close #1  SaveSetting "ump3v2", "settings", "ini file", App.PATH & "" & filenameEnd Sub

what i get is :

[Ump3 V2 ini file]

everything ok here.. BUT ... instead of giving me TRUE OR FALSE it gives me the values WAAR (true) and onwaar (FALSE well un true to be freely translating but still) this is really anoying because onload of my form i cant read those values into a boolean .... how to fix this stupid saving thing???

running on windows XP pro , Sp1 , Vb6

Direct3D Hook Dll?
is there a direct3d hook dll available which would allow me to draw text over a directx game through visual basic?

i want to display an ingame clock and maybe an fps counter over ANY direct3d game...

i've found the proxy dll by after some searching....
it works nice for single games though and allows me todo everything i want
but it doesn't work when injected at runtime and i want my application to work generally in every direct3d game without having to copy a dll file to every games folder...

i want to inject the dll with madcodehook from (works fine with the example direct3d hook dll that comes with it) but unfortunately C is a complette mystery to me :X

thanks in advance for every point in the right direction

Copyright © 2005-08, All rights reserved