|
-
Sep 3rd, 2005, 01:52 AM
#1
Thread Starter
Fanatic Member
[RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
Hello..
Can someone help on how I can detect the mousedown,mouseup etc even outside my application using vb.net?
I have an API here,but,doesnt seem to work the way I expect it to..
VB Code:
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If GetAsyncKeyState(1) = "1" Then
Label1.Text = ("Left mouse button clicked")
Else
Label1.Text = "mouse button up"
End If
End Sub
Should that API be modified to be used or something?? or what should I do to capture the mouse click events..both left and right buttons...
Thanks
Last edited by uniquegodwin; Sep 4th, 2005 at 08:51 AM.
Godwin
Help someone else with what someone helped you! 
-
Sep 4th, 2005, 12:04 AM
#2
-
Sep 4th, 2005, 12:25 AM
#3
New Member
Re: Capturing mouse click event in vb.net
Thanks Thanks Thanks Mr Polite....
Yes,I do need help converting to vb.net if possible...Please help if u can,I would be really grateful.
Thanks again so much,..
And about the frogs,there r 10 frogs in the post totally
-
Sep 4th, 2005, 12:49 AM
#4
New Member
Re: Capturing mouse click event in vb.net
WOW,This code project link you gave me...That c# app is EXCELLENT...It works sooo perrrfecttlyyy when I execute it...
I tried searching on google on detecting mouse clicks...but never found a solution like this I wonder how u found it.It is Awesomeee...I will try figuring out to convert it into vb.net on my own and if Im not,Ill ask for help,please give me a hand if possible at that time...Thanks Mr.Polite
-
Sep 4th, 2005, 12:50 AM
#5
New Member
Re: Capturing mouse click event in vb.net
oops,never realised my classmates id was logged on here..ohh noo..i was posting thinking its my id...nevermind anyway..Its me Godwin right now
-
Sep 4th, 2005, 02:44 AM
#6
Re: Capturing mouse click event in vb.net
 Originally Posted by virtual_manu
Thanks Thanks Thanks Mr Polite....
Yes,I do need help converting to vb.net if possible...Please help if u can,I would be really grateful.
Thanks again so much,..
And about the frogs,there r 10 frogs in the post totally 
haha 10 including my sig
you got me so confused, I thought someone else wanted this same thing too lol
if you don't already have it, download Reflector
it's more like a decompiler, but in this case, if you try to decompile that codeproject sample to VB, it's a good tool for converting from C# to vb.net
minutes later...
listen, it turns out that my VB skills are fading away I copy pasted a lot of code from the decompiler and did everything that I could just to make it compile. I STRONGLY descourage you from using it,. it's most likely unsatble. I couldnt even find a nice way to add the event handlers in. ugh
the C# version isnt all that nice either. the guy uses classes where he could use structures (for the api calls)
for reference, in the next two posts
I didn't even double check ANYTHING. it's a horrible mess that I'm posting. I'm posting it in case you had trouble converting something from c# to vb... it compiles and the click events seem to work fine. But it won't detect mouse move, and the keyboard keys seem to get lost...
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Sep 4th, 2005, 02:45 AM
#7
Re: Capturing mouse click event in vb.net
VB Code:
Imports System.Runtime.InteropServices
Public Class UserActivityHook
Public Delegate Function HookProc(ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
Public KeyboardHookProcedure As HookProc
Public KeyDown As KeyEventHandler
Public KeyPress As KeyPressEventHandler
Public KeyUp As KeyEventHandler
Public OnMouseActivity As MouseEventHandler
Private Shared hKeyboardHook As Integer
Private Shared hMouseHook As Integer
Public MouseHookProcedure As HookProc
Public Const WH_KEYBOARD_LL As Integer = 13
Public Const WH_MOUSE_LL As Integer = 14
Private Const WM_KEYDOWN As Integer = 256
Private Const WM_KEYUP As Integer = 257
Private Const WM_LBUTTONDBLCLK As Integer = 515
Private Const WM_LBUTTONDOWN As Integer = 513
Private Const WM_LBUTTONUP As Integer = 514
Private Const WM_MBUTTONDBLCLK As Integer = 521
Private Const WM_MBUTTONDOWN As Integer = 519
Private Const WM_MBUTTONUP As Integer = 520
Private Const WM_MOUSEMOVE As Integer = 512
Private Const WM_RBUTTONDBLCLK As Integer = 518
Private Const WM_RBUTTONDOWN As Integer = 516
Private Const WM_RBUTTONUP As Integer = 517
Private Const WM_SYSKEYDOWN As Integer = 260
Private Const WM_SYSKEYUP As Integer = 261
#Region "dll imports"
' Methods
<DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)> _
Public Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
End Function
<DllImport("user32")> _
Public Shared Function GetKeyboardState(ByVal pbKeyState As Byte()) As Integer
End Function
<DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)> _
Public Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As HookProc, ByVal hInstance As IntPtr, ByVal threadId As Integer) As Integer
End Function
<DllImport("user32")> _
Public Shared Function ToAscii(ByVal uVirtKey As Integer, ByVal uScanCode As Integer, ByVal lpbKeyState As Byte(), ByVal lpwTransKey As Byte(), ByVal fuState As Integer) As Integer
End Function
<DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)> _
Public Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean
End Function
#End Region
#Region "Structures and whatnot"
<StructLayout(LayoutKind.Sequential)> _
Public Class KeyboardHookStruct
' Fields
Public dwExtraInfo As Integer
Public flags As Integer
Public scanCode As Integer
Public time As Integer
Public vkCode As Integer
End Class
<StructLayout(LayoutKind.Sequential)> _
Public Class MouseHookStruct
' Fields
Public dwExtraInfo As Integer
Public hwnd As Integer
Public pt As POINT
Public wHitTestCode As Integer
End Class
<StructLayout(LayoutKind.Sequential)> _
Public Class POINT
' Fields
Public x As Integer
Public y As Integer
End Class
#End Region
Public Sub New()
Start()
End Sub
Protected Overrides Sub Finalize()
Try
Me.Stop()
Finally
MyBase.Finalize()
End Try
End Sub
Public Sub Start()
If (UserActivityHook.hMouseHook = 0) Then
Me.MouseHookProcedure = New HookProc(AddressOf Me.MouseHookProc)
UserActivityHook.hMouseHook = UserActivityHook.SetWindowsHookEx(14, Me.MouseHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)), 0)
If (UserActivityHook.hMouseHook = 0) Then
Me.Stop()
Throw New Exception("SetWindowsHookEx failed.")
End If
End If
If (UserActivityHook.hKeyboardHook = 0) Then
Me.KeyboardHookProcedure = New HookProc(AddressOf Me.KeyboardHookProc)
UserActivityHook.hKeyboardHook = UserActivityHook.SetWindowsHookEx(13, Me.KeyboardHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)), 0)
If (UserActivityHook.hKeyboardHook = 0) Then
Me.Stop()
Throw New Exception("SetWindowsHookEx ist failed.")
End If
End If
End Sub
Public Sub [Stop]()
Dim flag1 As Boolean = True
Dim flag2 As Boolean = True
If (UserActivityHook.hMouseHook <> 0) Then
flag1 = UserActivityHook.UnhookWindowsHookEx(UserActivityHook.hMouseHook)
UserActivityHook.hMouseHook = 0
End If
If (UserActivityHook.hKeyboardHook <> 0) Then
flag2 = UserActivityHook.UnhookWindowsHookEx(UserActivityHook.hKeyboardHook)
UserActivityHook.hKeyboardHook = 0
End If
If (Not flag1 OrElse Not flag2) Then
Throw New Exception("UnhookWindowsHookEx failed.")
End If
End Sub
Private Function MouseHookProc(ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
If ((nCode >= 0) AndAlso (Not Me.OnMouseActivity Is Nothing)) Then
Dim buttons1 As MouseButtons = MouseButtons.None
Dim num3 As Integer = wParam
If (num3 <> 513) Then
If (num3 = 516) Then
buttons1 = MouseButtons.Right
End If
Else
buttons1 = MouseButtons.Left
End If
Dim num1 As Integer = 0
If (buttons1 <> MouseButtons.None) Then
If ((wParam = 515) OrElse (wParam = 518)) Then
num1 = 2
Else
num1 = 1
End If
End If
Dim struct1 As MouseHookStruct = CType(Marshal.PtrToStructure(lParam, GetType(MouseHookStruct)), MouseHookStruct)
Dim args1 As New MouseEventArgs(buttons1, num1, struct1.pt.x, struct1.pt.y, 0)
Me.OnMouseActivity.Invoke(Me, args1)
End If
Return UserActivityHook.CallNextHookEx(UserActivityHook.hMouseHook, nCode, wParam, lParam)
End Function
Private Function KeyboardHookProc(ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
If ((nCode >= 0) AndAlso (((Not Me.KeyDown Is Nothing) OrElse (Not Me.KeyUp Is Nothing)) OrElse (Not Me.KeyPress Is Nothing))) Then
Dim struct1 As KeyboardHookStruct = CType(Marshal.PtrToStructure(lParam, GetType(KeyboardHookStruct)), KeyboardHookStruct)
If ((Not Me.KeyDown Is Nothing) AndAlso ((wParam = 256) OrElse (wParam = 260))) Then
Dim args1 As New KeyEventArgs(CType(struct1.vkCode, Keys))
Me.KeyDown.Invoke(Me, args1)
End If
If ((Not Me.KeyPress Is Nothing) AndAlso (wParam = 256)) Then
Dim buffer1 As Byte() = New Byte(256 - 1) {}
UserActivityHook.GetKeyboardState(buffer1)
Dim buffer2 As Byte() = New Byte(2 - 1) {}
If (UserActivityHook.ToAscii(struct1.vkCode, struct1.scanCode, buffer1, buffer2, struct1.flags) = 1) Then
Dim args2 As New KeyPressEventArgs(Convert.ToChar(buffer2(0)))
Me.KeyPress.Invoke(Me, args2)
End If
End If
If ((Not Me.KeyUp Is Nothing) AndAlso ((wParam = 257) OrElse (wParam = 261))) Then
Dim args3 As New KeyEventArgs(CType(struct1.vkCode, Keys))
Me.KeyUp.Invoke(Me, args3)
End If
End If
Return UserActivityHook.CallNextHookEx(UserActivityHook.hKeyboardHook, nCode, wParam, lParam)
End Function
End Class
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Sep 4th, 2005, 02:46 AM
#8
Re: Capturing mouse click event in vb.net
VB Code:
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents textBox As System.Windows.Forms.TextBox
Friend WithEvents labelMousePosition As System.Windows.Forms.Label
Friend WithEvents buttonStop As System.Windows.Forms.Button
Friend WithEvents buttonStart As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.textBox = New System.Windows.Forms.TextBox
Me.labelMousePosition = New System.Windows.Forms.Label
Me.buttonStop = New System.Windows.Forms.Button
Me.buttonStart = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'textBox
'
Me.textBox.Font = New System.Drawing.Font("Courier New", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World)
Me.textBox.Location = New System.Drawing.Point(8, 126)
Me.textBox.Multiline = True
Me.textBox.Name = "textBox"
Me.textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.textBox.Size = New System.Drawing.Size(280, 240)
Me.textBox.TabIndex = 7
Me.textBox.Text = ""
'
'labelMousePosition
'
Me.labelMousePosition.Location = New System.Drawing.Point(40, 94)
Me.labelMousePosition.Name = "labelMousePosition"
Me.labelMousePosition.Size = New System.Drawing.Size(184, 23)
Me.labelMousePosition.TabIndex = 6
Me.labelMousePosition.Text = "labelMousePosition"
'
'buttonStop
'
Me.buttonStop.Location = New System.Drawing.Point(144, 46)
Me.buttonStop.Name = "buttonStop"
Me.buttonStop.TabIndex = 5
Me.buttonStop.Text = "Stop"
'
'buttonStart
'
Me.buttonStart.Location = New System.Drawing.Point(40, 46)
Me.buttonStart.Name = "buttonStart"
Me.buttonStart.TabIndex = 4
Me.buttonStart.Text = "Start"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(296, 413)
Me.Controls.Add(Me.textBox)
Me.Controls.Add(Me.labelMousePosition)
Me.Controls.Add(Me.buttonStop)
Me.Controls.Add(Me.buttonStart)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
Private actHook As UserActivityHook
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.actHook = New UserActivityHook
Me.actHook.OnMouseActivity = New MouseEventHandler(AddressOf MouseMoved)
Me.actHook.KeyDown = New KeyEventHandler(AddressOf MyKeyDown)
Me.actHook.KeyPress = New KeyPressEventHandler(AddressOf MyKeyPress)
Me.actHook.KeyUp = New KeyEventHandler(AddressOf MyKeyUp)
End Sub
Private Sub buttonStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonStart.Click
actHook.Start()
End Sub
Private Sub buttonStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonStop.Click
actHook.Stop()
End Sub
Public Sub MouseMoved(ByVal sender As Object, ByVal e As MouseEventArgs)
Me.labelMousePosition.Text = String.Format("x={0} y={1}", e.X, e.Y)
If (e.Clicks > 0) Then
Me.LogWrite(("MouseButton " & ChrW(9) & "- " & e.Button.ToString))
End If
End Sub
Public Sub MyKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
Me.LogWrite(("KeyDown " & ChrW(9) & "- " & e.KeyData.ToString))
End Sub
Public Sub MyKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
Me.LogWrite(("KeyPress " & ChrW(9) & "- " & e.KeyChar))
End Sub
Public Sub MyKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs)
Me.LogWrite(("KeyUp " & ChrW(9) & ChrW(9) & "- " & e.KeyData.ToString))
End Sub
Private Sub LogWrite(ByVal txt As String)
Me.textBox.AppendText((txt & Environment.NewLine))
Me.textBox.SelectionStart = Me.textBox.Text.Length
End Sub
End Class
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Sep 4th, 2005, 08:38 AM
#9
Thread Starter
Fanatic Member
Re: Capturing mouse click event in vb.net
Mr.Polite,Thank you so so so so sooo muchhhh...
The detecting click was the main thing.Im trying to make an open source remote desktop application..its opensource..but,all source isnt mine though..i took some code from the internet too to help me with it I wonder if I have to ask their permission to make it opensource.
Never mind the mouse move Mr.Polite ..
for the mouse move,I was already using this concept to get it...
VB Code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Me.Text = Cursor.Position.X & "x" & Cursor.Position.Y
End Sub
Thanks again Mr.Polite I did do a little bit reading on the windows hook thing,but it was about some kind of messages passed between windows or something and theres some point there which we control? something like that,i understood something..im not clear how exactly we are able to detect mouse using this windows hook.Ill still read again and further and try to understand.Thank you so much Mr.Polite
Godwin
Help someone else with what someone helped you! 
-
Sep 18th, 2005, 12:43 AM
#10
Re: [RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
Mr.Polite
is there a way to use that class you posted to have a timer be enabled only with the left mouse button is pressed?
ie: if the user holds down the left mouse button (even outside of this application) a timer is going, but as soon as the left mouse button is no longer being pressed the timer is set to false?
-
Oct 6th, 2009, 07:02 PM
#11
Junior Member
Re: [RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
Conctact me if you need help with Hooking please... I have written and taught how to perform Low Level Hooks in VB.NET and C# and can explain clearly the entire process as well as distribute professionally written code.
-
Dec 31st, 2009, 03:36 AM
#12
New Member
Re: [RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
I am a beginner in VB.net and I cannot figure out how to do a mouseclick hook.
I know how to do it on forms but I get totally lost on the API and other stuff.
If someone can please walk me through the process step by step I would really appreciate it. My yahoo messenger id is x_shakespear_x
Or you can post it up here as a tutorial, because I know I cannot be the only one that is totally lost over the whole Hook scenario.
-
Nov 2nd, 2010, 07:35 AM
#13
New Member
Re: [RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
Sorry for reopening a resolved post. I have tried running the above code. Unfortunately it runs into the exception on line 112 in the UserActivityHook class.
Code:
Throw New Exception("SetWindowsHookEx failed.")
I look back the code and found out that on line 109
Code:
UserActivityHook.hMouseHook = UserActivityHook.SetWindowsHookEx(14, Me.MouseHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)), 0)
the function SetWindowsHookEx does not return a value and when i look back at the function on line 46 to 48 and found out that there is nothing in the function.
Code:
<DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)> _
Public Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As HookProc, ByVal hInstance As IntPtr, ByVal threadId As Integer) As Integer
End Function
I am not familiar with DllImport. Did i miss out something? Do i need to add any reference or import any dll into this project? I believe i must have missed out some steps. Please advise. Thanks a lot in advance.
-
Nov 2nd, 2010, 11:51 PM
#14
New Member
Re: [RESOLVED]Capturing mouse click event in vb.net(Thanks so much Mr.Polite)
Juz saw this FAQ question in the link above. Done that and tested that. Works fine. Sorry for not going through the link before asking.. 
Question
The project cannot be run in Visual Studio .NET 2005 in debug mode because of an exception error caused by calling the SetWindowsHookEx. Why? Is it a problem of .NET 2.0?
Answer
The compiled release version works well so that cannot be a .NET 2.0 problem. To workaround, you just need to uncheck the check box in the project properties that says: "Enable Visual Studio hosting process". In the menu: Project -> Project Properties... -> Debug -> Enable the Visual Studio hosting process.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|