Actually, I want to create a service to detect if "any key" is pressed.
However, the following module works if I compile it with a Form. But it does not work if I compile it and called setHook() in a service project.
I have configured it as running with logon as Local System and Enable to interact with desktop.
Imports System.IO
Imports System.Runtime.InteropServices
Module Module1
Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName) As Integer
Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Integer, ByVal lpfn As HOOKPROC, ByVal hmod As Integer, ByVal dwThreadId As Integer) As Integer
Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Integer) As Integer
Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Integer, ByVal ncode As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
Public Delegate Function HOOKPROC(ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
Public Function MyKeyboardProc(ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
If Not nCode < 0 Then
Dim sw As StreamWriter = New StreamWriter("c:\test1.txt", True)
sw.WriteLine("Test HOOK")
sw.Close()
MyKeyboardProc = CallNextHookEx(hnexthookproc, nCode, wParam, lParam)
End If
End Function
<MarshalAs(UnmanagedType.FunctionPtr)> Private callback As HOOKPROC
Public hnexthookproc As Integer = 0
Public Const PM_KEY_SPACE = &H20
Public Enum HookType
WH_KEYBOARD_LL = 13
WH_MOUSE_LL = 14
End Enum
Public Sub UnHook()
If hnexthookproc <> 0 Then
UnhookWindowsHookEx(hnexthookproc)
hnexthookproc = 0
End If
End Sub
Public Function SetHook()
callback = New HOOKPROC(AddressOf MyKeyboardProc)
If hnexthookproc <> 0 Then
Exit Function
End If
hnexthookproc = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, callback, Marshal.GetHINSTANCE(Reflection.Assembly.GetExecutingAssembly().GetModules()(0)), 0)
Dim sw As StreamWriter = New StreamWriter("c:\test.txt", True)
sw.WriteLine(hnexthookproc)
sw.Close()
End Function
End Module
I am a newcomer of VB.Net. But I really wanted to know the mistakes I made.
Thank you :-O