How to use the Paint event to draw shapes at mouse coordinates

前端 未结 4 2030
说谎
说谎 2020-11-27 08:24

I recently started programming in C# obviously and was trying to do a simple WinForms app that takes mouse coordinates and scales a Rectangle accor

4条回答
  •  盖世英雄少女心
    2020-11-27 09:05

    Drawing in WinForms application works in a slightly different way then you probably expect. Everything on screen now is considered to be temporary, if you e.g. minimize and restore your window, the onscreen stuff will be erased and you'll be asked to repaint it again (your window's Paint event will be fired by the system).

    That's why that DrawRect method expects PaintEventArgs argument: it is supposed to be called only withing your Paint event handler. If you call it from outside (like it is suggested in other answer) your rectangles might behave inconsistently.

    I would suggest remember your rectangles in some internal variable and then repaint them when asked for that by the system:

    private Point pointToDrawRect = new Point(0,0);
    public void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            int x = e.X;
            int y = e.Y;
            String data = (x.ToString() + " " + y.ToString());
            pointToDrawRect= new Point(x, y);
            Invalidate();
        }
    
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
             if(pointToDrawRect.X != 0 || pointToDrawRect.Y != 0)
             {
                 DrawRect(e, pointToDrawRect.X, pointToDrawRect.Y);
             }
        }
    
        public void DrawRect(PaintEventArgs e, int rey, int rex)
        {
                using (Pen pen = new Pen(Color.Azure, 4))
                {
                    Rectangle rect = new Rectangle(0, 0, rex, rey);
                    e.Graphics.DrawRectangle(pen, rect);
                }
        }
    

提交回复
热议问题