Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a global mouse hook. When the user left-clicks inside a window (can be any application), I want to get this window's handle and move it. I have the following functions that I use to move the window and get the window at the mouse coordinates:

VB
<DllImport("user32.dll", SetLastError:=True)> _
Public Shared Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As UInt32) As Boolean
End Function


VB
<DllImport("user32.dll", EntryPoint:="WindowFromPoint", CharSet:=CharSet.Auto, ExactSpelling:=True)> _
Public Shared Function WindowFromPoint(ByVal pt As Point) As IntPtr
End Function


Here is where the program detects the left-clicks:

VB
Public Sub MouseMoved(ByVal sender As Object, ByVal e As MouseEventArgs)
    If (e.Clicks > 0 AndAlso e.Button = Windows.Forms.MouseButtons.Left) Then
        SetWindowPos(WindowFromPoint(New Point(Cursor.Position.X, Cursor.Position.Y)), New IntPtr(-1), 200, 200, SomeWidth, SomeHeight, 0)
    End If
End Sub


This should move the window to coordinates 200, 200 and resize it to SomeWidth/SomeHeight (whatever those are).

Currently, it works as desired if I click in the title bar or the window's edge (resize cursor appears), but it does not work if the user clicks inside the window - ie. the user clicks inside an IE window in the control where the pages load. Clicking anywhere but on the title bar or window edge returns a different handle than the window handle, and so the window is not moved. How can I get the window's handle no matter where the user clicks inside this window?

Thanks.
Posted

It sounds like everything is working properly, but your understanding or terminology is a bit off. The code is correctly picking up the window underneath the cursor, but that window is often a child window. If I'm understanding your question correctly, you are looking to always find the main parent window that is underneath the cursor. Try taking the handle you get from WindowFromPoint and passing it to the GetAncestor[^] function with the GA_ROOT flag. If the result of the GetAncestor is not NULL, use that handle; otherwise use the handle from the original WindowFromPoint call.
 
Share this answer
 
Check this thread on the MSDN Message Board[^]. Looks like it should answer your question. :)

Flynn
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900