Reputation: 117
I writing a C# application. I am looking a way to find a window handle of the controls in other applications by just giving the coordinates of the mouse click (or for that matter any coordinates).
Example: On my desktop, I have calculator application opened, notepad opened and some other 3rd party application running. Screen is covered partially by each of them. Now if I run my application and if I click at any location on the screen, I want to be able to find out the window handle of the control (button, textbox, label, tab, frame, etc.) under the mouse irrespective if it was clicked on a button in calculator, File menu in notepad, or some other control in the 3rd party application. It is similar to the functionality we get from Spy++.
Upvotes: 1
Views: 6755
Reputation: 4007
you have to set global Windows hook for mouse events. This will cause yours application to get mouse (or keyboard) clicks in foreign windows.
Please find this article on code project as sample C# wrapper on Windows API. Windows API functions are listed in the article too
Upvotes: 0
Reputation: 1503
Use Windows hook for mouse events (like oleksa said) then this PInvoke to get the foreground window : http://www.pinvoke.net/default.aspx/user32.getforegroundwindow
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
void yourFonction(){
[...]
IntPtr handleTopMostWindow = GetForegroundWindow();
}
you just need to call this method in your code to retrieve the window's foreground handle :
Upvotes: 0
Reputation: 3897
BTW, this has already been done for you, sounds like all you need is to clone the repo then customize to your hearts content.
I don't think Global Hooks would be necessary.
You should be able to use any number of methods to get cursor position, hooking is just going to complicate things. For example, you can try the following:
using System;
using System.Windows;
using System.Windows.Input;
using System.Runtime.InteropServices;
namespace Namespace1
{
class Class1
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
}
}
Then you just need a few Pinvoke signatures.
Namely, WindowFromPoint and EnumChildWindows.
Refer to "Enumerating Windows/Controls of another application from .Net".
Hope that helps.
Good luck.
Upvotes: 4