Okay so I'm trying to make a little gag program that will "run away" from the mouse.
So, to get the mouse coordinates for the whole screen and not just the form control I had to create a little helper:
static class MouseHelper
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Point pt);
public static Point GetPosition()
{
Point w32Mouse = new Point();
GetCursorPos(ref w32Mouse);
return w32Mouse;
}
}
Now I thought I was going to use the MouseMove event... but that doesn't work for outside the form control either so I have an auto-enabled timer on a 10ms loop called timerMouseMove.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool CollisionCheck()
{
Point win32Mouse = 开发者_运维知识库MouseHelper.GetPosition();
if (win32Mouse.X <= Location.X || win32Mouse.X >= (Location.X + Width))
return false;
if (win32Mouse.Y <= Location.Y || win32Mouse.Y >= (Location.Y + Height))
return false;
return true;
}
private void timerMouseMove_Tick(object sender, EventArgs e)
{
if (CollisionCheck())
Location = new Point(Location.X + 1, Location.Y + 1);
}
}
So this works out nicely, at least I have the collision checking working and whatnot. But now, how should I go about figuring which side of the form the mouse has collided with, so that I can update its location to move in the opposite direction the mouse collides with it? And such halp
You're capturing the mouse position over time, so you can infer the direction if you keep a "this position" and "last position". You could even calculate the velocity, and move the form a greater distance if the mouse is moving faster.
Happy April Fool's!
精彩评论