Havion
Havion

Reputation: 29

C# specific Point issue

Alright I am slowly building a drawing program for fun and practice but I have a specific problem. Here is my code.

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
         Pen p = new Pen(Color.Black, 4);
         Graphics g = panel1.CreateGraphics();
         g.DrawRectangle(p, start.X, start.Y, 20, 20);
    }
    Control control = (Control)sender;
    start = control.PointToScreen(new Point(e.X, e.Y));
}

Now this draws a rectangle at 0, 0 on the panel on the first click as expected as a test because the start variable is after the if statement. The problem is the next clicks draw the rectangle way below where I clicked on the panel. If I click near the top of the panel it draws these rectangles near the bottom but it seems to atleast notice my mouse is in a different position each time.

If any of you could figure out the mistake I am making and explain it would help loads! thanks!

Upvotes: 0

Views: 66

Answers (1)

Rob
Rob

Reputation: 27367

Change this:

start = control.PointToScreen(new Point(e.X, e.Y));

To this:

start = new Point(e.X, e.Y);

This fixes your immediate problem, but is your goal really to draw a rectangle at the position of your last click, and not current one?

Anyway, the issue you had is that the x,y co-ordinates you were saving were relative to the screen, not to the control

As per your comment, this draws a rectangle wherever you click (no need for the start variable anymore:

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Pen p = new Pen(Color.Black, 4);
        Graphics g = panel1.CreateGraphics();
        g.DrawRectangle(p, e.X, e.Y, 20, 20);
    }
}

Upvotes: 3

Related Questions