Hook system mouse down?

S

schneider

I need to hook the system mouse down event.

I'm trying to replicate how a context menu hides when the mouse clicks
outside of the control.

Thanks,

Schneider
 
T

Tom Shelton

schneider said:
I need to hook the system mouse down event.

I'm trying to replicate how a context menu hides when the mouse clicks
outside of the control.

Thanks,

Schneider

I'm assuming you want to be able to get the mouse anywhere on the screen.
If you only mean in your app, then you would handle the mouse events for
your form - otherwise you can look at this sample :) This needs a lot more
work to be complete - but here is a sample of installing a global mouse
hook. The work that needs to be done is in the HookProc in the
GlobalMouseHook class. You can use the information that is passed to
actually send information to the event (that's why I used the
mouseeventhandler). You also have access to mouse wheel info if you so
desire. Anyway, here is a basic example, watch for wrap :)

Option Strict On
Option Explicit On
Option Infer Off

Imports System.Runtime.InteropServices

Public Class Form1
Inherits System.Windows.Forms.Form

Public Sub New()
InitializeComponent()
End Sub

#Region "Designer Code"
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
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.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.ListBox1 = New System.Windows.Forms.ListBox
Me.SuspendLayout()
'
'ListBox1
'
Me.ListBox1.Dock = System.Windows.Forms.DockStyle.Fill
Me.ListBox1.FormattingEnabled = True
Me.ListBox1.IntegralHeight = False
Me.ListBox1.Location = New System.Drawing.Point(0, 0)
Me.ListBox1.Name = "ListBox1"
Me.ListBox1.Size = New System.Drawing.Size(284, 264)
Me.ListBox1.TabIndex = 0
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(284, 264)
Me.Controls.Add(Me.ListBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)

End Sub
Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
#End Region

Private WithEvents gmh As GlobalMouseHook

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
gmh = New GlobalMouseHook()

End Sub

Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
gmh.Dispose()
End Sub

Private Sub gmh_MouseDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles gmh.MouseDown
Me.ListBox1.Items.Add(String.Format("{0} down at screen coordinate
({1},{2})", e.Button, e.X, e.Y))
End Sub

Private Sub gmh_MouseMove(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles gmh.MouseMove
'Me.ListBox1.Items.Add("Move")
End Sub

Private Sub gmh_MouseUp(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles gmh.MouseUp
Me.ListBox1.Items.Add("Up")
End Sub
End Class


Friend Class GlobalMouseHook
Implements IDisposable

Private hhk As IntPtr = IntPtr.Zero
Private disposedValue As Boolean = False ' To detect redundant
calls

Public Event MouseDown As MouseEventHandler
Public Event MouseUp As MouseEventHandler
Public Event MouseMove As MouseEventHandler

Public Sub New()
Hook()
End Sub

Private Sub Hook()
Dim hInstance As IntPtr = LoadLibrary("User32")
hhk = SetWindowsHookEx(WH_MOUSE_LL, AddressOf Me.HookProc,
hInstance, 0)
End Sub

Private Sub Unhook()
UnhookWindowsHookEx(hhk)
End Sub

Private Function HookProc(ByVal nCode As Integer, ByVal wParam As
UInteger, ByRef lParam As MSLLHOOKSTRUCT) As Integer
If nCode >= 0 Then
Select Case wParam
Case WM_LBUTTONDOWN
RaiseEvent MouseDown(Me, New
MouseEventArgs(MouseButtons.Left, 0, lParam.pt.x, lParam.pt.y, 0))
Case WM_RBUTTONDOWN
RaiseEvent MouseDown(Me, New
MouseEventArgs(MouseButtons.Right, 0, lParam.pt.x, lParam.pt.y, 0))
Case WM_MBUTTONDOWN
RaiseEvent MouseDown(Me, New
MouseEventArgs(MouseButtons.Middle, 0, lParam.pt.x, lParam.pt.y, 0))
Case WM_LBUTTONUP, WM_RBUTTONUP, WM_MBUTTONUP
RaiseEvent MouseUp(Nothing, Nothing)
Case WM_MOUSEMOVE
RaiseEvent MouseMove(Nothing, Nothing)
Case WM_MOUSEWHEEL, WM_MOUSEHWHEEL
Case Else
Console.WriteLine(wParam)
End Select
End If
Return CallNextHookEx(hhk, nCode, wParam, lParam)
End Function

#Region "API Declarations"
<StructLayout(LayoutKind.Sequential)> _
Private Structure API_POINT
Public x As Integer
Public y As Integer
End Structure

<StructLayout(LayoutKind.Sequential)> _
Private Structure MSLLHOOKSTRUCT
Public pt As API_POINT
Public mouseData As UInteger
Public flags As UInteger
Public time As UInteger
Public dwExtraInfo As IntPtr
End Structure

Private Const WM_MOUSEWHEEL As UInteger = &H20A
Private Const WM_MOUSEHWHEEL As UInteger = &H20E
Private Const WM_MOUSEMOVE As UInteger = &H200
Private Const WM_LBUTTONDOWN As UInteger = &H201
Private Const WM_LBUTTONUP As UInteger = &H202
Private Const WM_MBUTTONDOWN As UInteger = &H207
Private Const WM_MBUTTONUP As UInteger = &H208
Private Const WM_RBUTTONDOWN As UInteger = &H204
Private Const WM_RBUTTONUP As UInteger = &H205
Private Const WH_MOUSE_LL As Integer = 14

Private Delegate Function LowLevelMouseHookProc(ByVal nCode As Integer,
ByVal wParam As UInteger, ByRef lParam As MSLLHOOKSTRUCT) As Integer

Private Declare Auto Function LoadLibrary Lib "kernel32" (ByVal
lpFileName As String) As IntPtr
Private Declare Auto Function SetWindowsHookEx Lib "user32.dll" (ByVal
idHook As Integer, ByVal lpfn As LowLevelMouseHookProc, ByVal hInstance As
IntPtr, ByVal dwThreadId As UInteger) As IntPtr
Private Declare Function CallNextHookEx Lib "user32" (ByVal hhk As
IntPtr, ByVal nCode As Integer, ByVal wParam As UInteger, ByRef lParam As
MSLLHOOKSTRUCT) As Integer
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hhk As
IntPtr) As Boolean
#End Region



' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free other state (managed objects).
End If

Unhook()
End If
Me.disposedValue = True
End Sub

#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable
pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal
disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region

End Class
 
C

Cor Ligthert[MVP]

Tom,

Nice sample, I always am curious why people are using for describing window
messages those UpperCase words.

I never saw any reason for that, however by that so frequent use of that, it
gives the idea that it is needed.

Can you tell what is it, that I am missing?

Or is it just conventional stuff used in past in VB6 and C*?

Cor
 
J

Jialiang Ge [MSFT]

Hello Schneider,

From your post, my understanding on this issue is: how to hook the system
mouse down event in VB.NET. If I'm off base, please feel free to let me
know.

There are generally two different types of system hook: local system hook
(set a hook that is specific to a thread and to a hook procedure) and
global system hook (a system hook that is called when the specified
messages are processed by any application on the entire system.). Would you
let me know which type of hook you referred to?

If you meant local system hook, I'd suggest the KB article
http://support.microsoft.com/kb/319524. The WH_MOUSE hook enables you to
monitor mouse messages about to be returned by the GetMessage or
PeekMessage function. You can use the WH_MOUSE hook to monitor mouse input
posted to a message queue. To modify the code in the KB to hook mouse down
event, we can add a Select Case wParam statement in MouseHookProc, and
check if wParam equals WM_RBUTTONDOWN or WM_RBUTTONUP.

If you meant global system hook, There are WH_MOUSE_LL hooks that can be
installed globally. The code in
http://www.colinneller.com/blog/PermaLink,guid,2838f59a-f4af-4c95-a322-b9ee5
918a39c.aspx provides an example in VB.NET, which exposes a OnMouseUp event
we can utilize. For more readings about global system hook in .NET, please
refer to the codeproject article:
http://www.codeproject.com/KB/system/globalsystemhook.aspx
http://www.codeproject.com/KB/cs/globalhook.aspx

Let me know if you have any other concerns or questions.

Regards,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
T

Tom Shelton

Tom,

Nice sample, I always am curious why people are using for describing window
messages those UpperCase words.

I never saw any reason for that, however by that so frequent use of that, it
gives the idea that it is needed.

Can you tell what is it, that I am missing?

Or is it just conventional stuff used in past in VB6 and C*?

Cor

It's just a convention. It's easier to use the sdk documentation when
you name them the same :)
 
E

eschneider

I think I need a system wide hook. I'm reinventing the wheel by building my
own Context Menu. So if someone clicks anywhere while my context menu is
open I need to possibly hide the menu.

Any samples related to the menu would be a plus also.

I'm surprised there is not way to do this with-out using old API calls...

Thanks,
Schneider
 
S

schneider

Ok the debug error is gone now, not sure what was happening...

Restarted VS and was fine.
 
T

Tom Shelton

No error, just never raised events. Maybe OS issue? I'm on XP 64

Interesting - since my code is almost identical, at least in the
particulars. I purposely wasn't handling much of the mouse stuff
simply because it was a sample. Unfortunately, I don't have an XP64
system to test on :)
 
C

Cor Ligthert[MVP]

Joergen,

I know, but does that mean that you have to write them in Upercases like as
in the C++ documentation is done?.

Toms answer was just what I expected, that he would give, however there was
a slight chance it would have been different.

Cor
 
T

Tom Shelton

Joergen,

I know, but does that mean that you have to write them in Upercases like as
in the C++ documentation is done?.

Toms answer was just what I expected, that he would give, however there was
a slight chance it would have been different.

Cor

Cor,

According to Microsofts "Design Guidelines for Class Library
Developers" (http://msdn.microsoft.com/en-us/library/czefa0ke(VS.
71).aspx) - this is the appropriate style when dealing with native
interop. From the section on uppercase capitalization style:

<quote>
You might also have to capitalize identifiers to maintain
compatibility with existing, unmanaged symbol schemes, where all
uppercase characters are often used for enumerations and constant
values. In general, these symbols should not be visible outside of the
assembly that uses them.
</quote>

This is the recommendation I follow - I use the same name and
captialization for native interop contants and parameters. I also
don't expose them outside of the assembly. In other words, they
generally aren't part of the public interface.
 
T

Tom Shelton

Interesting - since my code is almost identical, at least in the
particulars. I purposely wasn't handling much of the mouse stuff
simply because it was a sample. Unfortunately, I don't have an XP64
system to test on :)

The only material difference that I can see in the comparison, is the
call to LoadLibrary. I removed that, and just passed in IntPtr.Zero and
it sill works. I wonder if that is the difference on a 64-bit
system....
 
J

Jialiang Ge [MSFT]

Hello,

Sorry for my delayed response. I was sick and stayed at home yesterday.

I notice you use a 64bit system. As far as I know, the way 64bit debugging
works in Visual Studio is by doing local remote debugging, which uses a
different version of msvsmon from the real remote debugging. Without an
event log, I cannot tell the exact reason for the stop of msvsmon on your
side. But I know if msvsmon stops, we will receive the error "The
Miscrosoft Visual Studio Remote Debugging Monitor has been closed on the
remote machine.". Restarting VS or repairing VS installation can resume
msvsmon.
Any samples related to the menu would be a plus also.

Schneider, I want to win the plus. Would you let me know the type of
Context Menu you want to disable? Is it a shell (windows explorer) context
menu? Would you give me more background information about the task?

Thanks,
Jialiang Ge ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

This posting is provided "AS IS" with no warranties, and confers no rights.
=================================================
 
H

Herfried K. Wagner [MVP]

Cor Ligthert said:
I know, but does that mean that you have to write them in Upercases like
as in the C++ documentation is done?.

Yes, because it enables the reader to look up the documentation on the
messages easily. In addition, any programmer familiar with the Win32 API
will be able to understand the code.
 
H

Herfried K. Wagner [MVP]

Tom Shelton said:
I'm assuming you want to be able to get the mouse anywhere on the screen.
If you only mean in your app, then you would handle the mouse events for
your form - otherwise you can look at this sample :) This needs a lot
more work to be complete - but here is a sample of installing a global
mouse hook. The work that needs to be done is in the HookProc in the
GlobalMouseHook class. You can use the information that is passed to
actually send information to the event (that's why I used the
mouseeventhandler). You also have access to mouse wheel info if you so
desire. Anyway, here is a basic example, watch for wrap :)
[...] Private Const WM_MOUSEWHEEL As UInteger = &H20A
Private Const WM_MOUSEHWHEEL As UInteger = &H20E
Private Const WM_MOUSEMOVE As UInteger = &H200
Private Const WM_LBUTTONDOWN As UInteger = &H201
Private Const WM_LBUTTONUP As UInteger = &H202
Private Const WM_MBUTTONDOWN As UInteger = &H207
Private Const WM_MBUTTONUP As UInteger = &H208
Private Const WM_RBUTTONDOWN As UInteger = &H204
Private Const WM_RBUTTONUP As UInteger = &H205
Private Const WH_MOUSE_LL As Integer = 14

Note that only the low-level hooks (based on message passing) can be used as
global hooks in VB.NET because managed libraries cannot export functions as
C libraries do. The disadvantage of the low-level hooks is that they are
very costly in terms of system resources.
 
T

Tom Shelton

Tom Shelton said:
I'm assuming you want to be able to get the mouse anywhere on the screen.
If you only mean in your app, then you would handle the mouse events for
your form - otherwise you can look at this sample :) This needs a lot
more work to be complete - but here is a sample of installing a global
mouse hook. The work that needs to be done is in the HookProc in the
GlobalMouseHook class. You can use the information that is passed to
actually send information to the event (that's why I used the
mouseeventhandler). You also have access to mouse wheel info if you so
desire. Anyway, here is a basic example, watch for wrap :)
[...] Private Const WM_MOUSEWHEEL As UInteger = &H20A
Private Const WM_MOUSEHWHEEL As UInteger = &H20E
Private Const WM_MOUSEMOVE As UInteger = &H200
Private Const WM_LBUTTONDOWN As UInteger = &H201
Private Const WM_LBUTTONUP As UInteger = &H202
Private Const WM_MBUTTONDOWN As UInteger = &H207
Private Const WM_MBUTTONUP As UInteger = &H208
Private Const WM_RBUTTONDOWN As UInteger = &H204
Private Const WM_RBUTTONUP As UInteger = &H205
Private Const WH_MOUSE_LL As Integer = 14

Note that only the low-level hooks (based on message passing) can be used as
global hooks in VB.NET because managed libraries cannot export functions as
C libraries do. The disadvantage of the low-level hooks is that they are
very costly in terms of system resources.

True. But, it's the only way to do it in .NET - unless your willing to
write an unmanaged dll.
 
E

eschneider

I am building my own Context Menu. I was working on the logic to hide the
menus when a user clicks somewhere outside of the popup menus.
I seem to have the menu working finally. This is the only low level API call
I have in all the code for the project. I hook before showing, then unhook
on the first instance of Mouse Down event outside the menus. I don't think
there is another way.

Thanks, Everyone

Schneider
 
C

Cor Ligthert[MVP]

">
Yes, because it enables the reader to look up the documentation on the
messages easily. In addition, any programmer familiar with the Win32 API
will be able to understand the code.
Herfried,

Which reader, do you mean a streaming Class?

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top