How to get a button handle of a third-party application using C #?

I am trying to create a click event in a third-party application. In the beginning I tried to simulate a click in a calculator. Here is the code "

IntPtr hwnd = IntPtr.Zero;
IntPtr hwndChild = IntPtr.Zero;
//Get a handle for the Calculator Application main window
hwnd = FindWindow(null, "Calculator");

hwndChild = FindWindowEx(hwnd, IntPtr.Zero, "Button", "1");

//send BN_CLICKED message
SendMessage(hwndChild, BM_CLICK, IntPtr.Zero, IntPtr.Zero);

But using this code, I do not get the button handle. Can someone help please. Is there any other way to simulate a button click on a third-party application?

Thank.

+3
source share
4 answers

It started working when I replaced

public const uint BM_CLICK = 0x00F5;

with

public const uint WM_LBUTTONDOWN = 0x0201; 
public const uint WM_LBUTTONUP = 0x0202;

and used

SendMessage(buttonHandle, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero); 
SendMessage(buttonHandle, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
+1
source

Your general approach is correct, but there are two potential problems with your code:

+1

SPY ++, .

, Button, . , Handle, Windows . . FindWindowEx

Also give the Parent window Handle (I think the first parameter, maybe you need to use GetWindow () using the signature)

Then send a click message.

0
source

If you do not have a button handle, you can emulate a mouse click on the coordinates:

class User32
 { 
    [Flags]
    public enum MouseEventFlags
    {
        LEFTDOWN = 0x00000002,
        LEFTUP = 0x00000004,
        MIDDLEDOWN = 0x00000020,
        MIDDLEUP = 0x00000040,
        MOVE = 0x00000001,
        ABSOLUTE = 0x00008000,
        RIGHTDOWN = 0x00000008,
        RIGHTUP = 0x00000010
    }

    [DllImport("user32.dll")]
    public static extern bool SetCursorPos(int X, int Y);

    [DllImport("user32.dll")]
    public static extern void mouse_event(uint dwFlags, 
                                   uint dx, 
                                   uint dy, 
                                   uint dwData,
                                   int dwExtraInfo);

    [DllImport("user32.dll")]
    public static extern void mouse_event(uint dwFlags, 
                                   uint dx, 
                                   uint dy, 
                                   uint dwData,
                                   UIntPtr dwExtraInfo);
}

class Program
{
     static void Main()
     {
         User32.SetCursorPos(25, 153);
         User32.mouse_event((uint)User32.MouseEventFlags.LEFTDOWN, 25, 153, 0, 0);
         User32.mouse_event((uint)User32.MouseEventFlags.LEFTUP, 25, 153, 0, 0);
     }
}

But, the SetCursorPos function sets the cursor position in the global coordinates of the screen, so you can access the window of a third-party application.

0
source

Source: https://habr.com/ru/post/1785944/


All Articles