ajm
ajm

Reputation: 101

Change label color on MouseHover, based on X Y coordinates

Without over-complicating a simple issue, I am trying to get the label color to change as the mouse hovers over a certain area of an image. My code should explain the situation:

    private void picboxMain_MouseHover(object sender, MouseEventArgs e)
    {
        int x1 = e.X;
        int y1 = e.Y;
        if ((x1 >= 155 && x1 <= 179) && (y1 >= 145 && y1 <= 160))
        {
            lblX.ForeColor = Color.Green;
            lblY.ForeColor = Color.Green;
        }
    }

However it will not accept the e.X and e.Y parameters which get the mouse location and assign to the x1 and y1 variables. Why will it not allow such variable assignment? I have successfully used this following almost identical function which works perfectly?

    private void picboxMain_MouseUp(object sender, MouseEventArgs e)
    {
        int x1 = e.X;
        int y1 = e.Y;
        if ((x1 >= 155 && x1 <= 179) && (y1 >= 145 && y1 <= 160))
        {
            Form2 Form2 = new Form2();
            Form2.Show();
        }
    }

Why does this work and not the other?

Upvotes: 1

Views: 171

Answers (1)

Dmitry
Dmitry

Reputation: 14059

Remove the MouseHover event handler, it doesn't contain MouseEventArgs in the second argument, and then add MouseMove handler with such code:

private void picboxMain_MouseMove(object sender, MouseEventArgs e)
{
    int x1 = e.X;
    int y1 = e.Y;
    Color color = (x1 >= 155 && x1 <= 179) && (y1 >= 145 && y1 <= 160) ? Color.Green : Color.Black;
    lblX.ForeColor = color;
    lblY.ForeColor = color;
}

EDIT: And also MouseLeave should be handled.

Upvotes: 5

Related Questions