What is the proper way to draw a line with mouse in C#

前端 未结 4 1100
盖世英雄少女心
盖世英雄少女心 2021-01-12 04:22

This is my drawing code to draw a custom line with mouse onto a Chart. Can you please help me to do it proper way ?

namespace Grafi
    {
        public p         


        
4条回答
  •  甜味超标
    2021-01-12 05:00

    Do you have any problems with your current implementation? Does it work, or do you just want to make the code better for an already working function.

    I think you logic looks just fine. However, I would add a using clause to the Pen like this:

    private void chartTemperature_MouseMove(object sender, MouseEventArgs e)
    {
      using( Pen p = new Pen(Color.Red, 2)){
        if (isDrawing)
        {
          Graphics g = chartTemperature.CreateGraphics();    
          g.DrawLine(p, prevPoint, e.Location);
          prevPoint = e.Location;
    
          numOfMouseEvents = 0;              
        }
      }
    }
    

    This way your Pen will be disposed even in case of any exceptions occuring after it's creation and your call to Dispose.

    However, you can also think of making the Pen a class variable so you don't have to create and dispose it each time you move the mouse.

提交回复
热议问题