问题
I am trying to move the mouse to a position(x, y), and click on it with the following code in a console c# application
[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
private const int MOUSEEVENTF_MOVE = 0x0001;
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int MOUSEEVENTF_ABSOLUTE = 0x8000;
public static void Move(int xDelta, int yDelta)
{
mouse_event(MOUSEEVENTF_MOVE, xDelta, yDelta, 0, 0);
}
public static void MoveTo(int x, int y)
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
}
public static void LeftClick()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
/* public static void LeftClick(int x, int y)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
*/
public static void LeftDown()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
public static void LeftUp()
{
mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
public static void RightClick()
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
public static void RightDown()
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
public static void RightUp()
{
mouse_event(MOUSEEVENTF_RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
click_position()
{
Cursor.Position = new Point(xwidth, yheight);
LeftClick
}
if the display scaling is at 100% it is working fine but if the display scaling is other than 100%, actual mouse click is different from the mouse co-ordinates. Please let me know any c# way to click on screen irrespective of display scaling in a console c# application
回答1:
If this is a windows desktop application then you would want to perform the click not on mouseposition only but subtract it with your window current position on both axis
For example:
public static void LeftClick() {
Point mousePosOnScreen = Cursor.Position - this.Location;
mouse_event(MOUSEEVENTF_LEFTDOWN, mousePosOnScreen.X, mousePosOnScreen.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, mousePosOnScreen.X, mousePosOnScreen.Y, 0, 0);
}
just a quick explanation of what you were doing wrong, when checking Cursor.Position will return the Pointer position on your monitor rather then on window. So by subtracting the window position you will end up with the position of the mouse pointer on your window.
来源:https://stackoverflow.com/questions/23903673/mouse-click-event-ir-respecive-of-display-scaling