开发者

C# Mouse Move and Click relative to active window

开发者 https://www.devze.com 2023-02-06 15:40 出处:网络
Hi I have been using code similar to this in a piece of automation I have been working on public static void LeftClick(int x, int y)

Hi I have been using code similar to this in a piece of automation I have been working on

public static void LeftClick(int x, int y)
{
    Cursor.Position = new System.Drawing.Point(x, y); //<= fails without this
    mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
    mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
}

However unless I am being dumb this move the mouse to the x,y from the top left of the screen which causes me problems 开发者_Go百科if the active window isn't where Im expecting it to be, can anyone suggest a way of achieving the same functionality with moving the mouse to a point relative to the active window.

Thanks


You need to pinvoke GetWindowRect() to find out where the window is located. So you can adjust x and y by the window position. Visit pinvoke.net for the declarations.


Just subtract the location (relative to the screen) of the window you are targeting.


What you're seeing is indeed the expected behavior. The Cursor.Position property describes the cursor's location in screen coordinates, not relative to your form.

However, every control exposes two handy methods that you can take advantage of to convert between screen coordinates and control coordinates:

  • The Control.PointToClient method computes the location of the specified screen point into client coordinates. Use this to convert from screen coordinates into client coordinates (i.e., those relative to your control, such as a form).

  • The Control.PointToScreen method computes the location of the specified client point into scren coordinates. Use this to convert from client coordinates into screen coordinates.


try PointToClient and PointToScreen of the control you are trying to find relative points to.

0

精彩评论

暂无评论...
验证码 换一张
取 消