Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleKnow when the user clicks on any control on a form
Keywordsform, click, control
CategoriesTips and Tricks, API, Controls
 
Normally a form doesn't get a Click event when the user clicks a control on the form.

Subclass and watch for the WM_MOUSEACTIVATE message. When you receive it, use the GetCursorPos API function to see where the mouse is. Use ScreenToClient to convert from screen coordinates into the form's coordinates in pixels.

 
' Process messages.
Public Function NewWindowProc(ByVal hwnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, ByVal lParam As Long) As _
    Long
Const WM_NCDESTROY = &H82

    ' If we're being destroyed,
    ' restore the original WindowProc.
    If msg = WM_NCDESTROY Then
        SetWindowLong _
            hwnd, GWL_WNDPROC, _
            OldWindowProc
    End If

    ' See if a control was clicked.
    If msg = WM_MOUSEACTIVATE Then Form1.MouseClicked

    NewWindowProc = CallWindowProc( _
        OldWindowProc, hwnd, msg, wParam, _
        lParam)
End Function
 
The form's MouseClicked subroutine uses the GetCursorPos API function to see where the mouse is. It then uses ScreenToClient to convert the mouse's position from screen coordinates to form coordinates. It draws an X on the form where the mouse is.
 
' The user clicked somewhere.
Public Sub MouseClicked()
Dim pt As POINTAPI

    ' See where the mouse is.
    GetCursorPos pt

    ' Convert into client coordinates.
    ScreenToClient hwnd, pt

    ' Draw a big X on the form where the mouse is.
    Cls
    Line (pt.X - 50, pt.Y - 50)-(pt.X + 50, pt.Y + 50)
    Line (pt.X + 50, pt.Y - 50)-(pt.X - 50, pt.Y + 50)
End Sub
 
Note that the WM_MOUSEACTIVATE message fires when the user clicks a control on the form. It does not fire when the user clicks the form itself (use the form's Click event to handle that). It also doesn't fire when the user clicks on a windowless control such as a Label.

For more information on subclassing including important precautions, see Tutorial: Subclassing.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated