Make winform run away from the mouse.

Posted by JACK IN THE CRACK on Stack Overflow See other posts from Stack Overflow or by JACK IN THE CRACK
Published on 2010-03-26T20:34:42Z Indexed on 2010/03/26 20:43 UTC
Read the original article Hit count: 344

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET