Link to home
Create AccountLog in
Avatar of Jonesey007
Jonesey007

asked on

Global Mouse Hook to find Windows Handles in C#

Hi,
I am incorperating a feature similar to that used in the Spy++ application.
I would like to click on a window (not my app) ie notepad, and be able to record the handle information.
I'm pretty sure i need a global mouse hook. If anyone knows how to do this with some pseudo code / tutorial or example
I would be very grateful
Thanks
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

In Spy++ you initiate the selection by dragging cross-hairs from Spy++ and dropping it on the target window.  Since the drag starts from within your app you do not need a global hook.  As long as the mouse is held down you will continue to get MouseMove() events in your app.  To get the target window you simply pass the current cursor position to WindowFromPoint() and then pass that handle to GetWindowRect() to obtain the dimensions.
Avatar of Jonesey007
Jonesey007

ASKER

Thanks very much for the information, do you think this is going to be alot of work to do using a type of Global hook?
I am currently reading "Processing Global Mouse and Keyboard Hooks in C#" on code project but it does not seem like a trivial task.
When the user presses a button on another application i need to record the window name and the button name when the mouse button is clicked so i can repeat the process later.
I think i need to study the CodeProject example listed above unless you have anyother idea's of a simpler way to achieve this?

Thanks
I'll almost done with an example...standby.
ASKER CERTIFIED SOLUTION
Avatar of _valkyrie_
_valkyrie_
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Hi Idle_Mind
Thank you so much for taking the time to write the example, sorry if this is a stupid question but is there a property i need to set to make the picturebox dragable?

Thanks
Pete
I didn't put in any visual cue for the PictureBox being dragged.  A really simply approach is to set the crosshairs cursor in the MouseDown() event:

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                pictureBox1.Cursor = Cursors.Cross;
            }
        }

Then set it back to Cursors.Default in the MouseUp() event.

You can make it more sophisticated by using a custom cursor if you want.  It's even possible to build a dynamic custom cursor from the image in the picturebox.
Thanks for the help guys