我有这段代码:
[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);
[Flags]
public enum MouseEventFlags
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
Absolute = 0x8000
}
public void SimMouseEvent(MouseEventFlags e, int x, int y)
{
mouse_event((uint)e, (uint)x, (uint)y, 0, UIntPtr.Zero);
}
public void SimLeftClick(int x, int y)
{
SimMouseEvent(MouseEventFlags.LeftUp | MouseEventFlags.RightUp, x, y);
}
我的表单如下:
单击“按钮”时,它会运行:
private void button3_Click(object sender, RoutedEventArgs e)
{
SimLeftClick(50, 50);
}
在我的窗口我也有这个:
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("click");
}
当我点击窗口时,它会按预期显示“点击”,但是当我点击“按钮”时,它似乎没有做任何事情。
坐标是绝对的还是相对的?多台显示器怎么样?他们只在专注的应用程序上工作吗?
我希望50,50能够在某个地方点击我的窗口然后点击“点击”处理程序或者点击一些随机窗口,因为它完全错过了我的应用程序并专注于那个......为什么不发生任何事情?< / p>
答案 0 :(得分:2)
答案 1 :(得分:1)
修正了Ben的建议。
public void SimLeftClick(int x, int y)
{
var scr = Screen.PrimaryScreen.Bounds;
SimMouseEvent(MouseEventFlags.LeftDown | MouseEventFlags.LeftUp | MouseEventFlags.Move | MouseEventFlags.Absolute,
(int)(x / (double)scr.Width * 65535),
(int)(y / (double)scr.Height * 65535));
}