如何使用鼠标单击事件和绘制窗体窗体图表控件的事件来绘制图表上的点?

时间:2015-05-14 08:56:29

标签: c# .net winforms

我现在添加了起点终点和鼠标x和鼠标y变量我想用它们在左键上点击鼠标时在图表控件上绘制点。

但我希望这些点只能在图表区域绘制,并且只有当鼠标位于图表中的方形区域内时才会绘制,因此它不会在方块边框线上或图表控制区域外绘制点。

还可以在图表中的方块中移动鼠标时显示,以显示标签上的轴X和轴Y值。

左轴1至120表示当前时间和底轴1至30当天。 因此,如果我在第一个方形区域移动鼠标,它应该显示第1天时间112或第2天时间33。

这就是为什么我也不确定X轴和Y轴的空间是否正确。 它应该是1到120和1到30但我认为每个方格应该在3天和120时间内出现但是在1步1的跳跃中所以当我用鼠标移动时我可以看到第一个方格第1天时间3或第3天时间66 下一排方格将显示第4至第6天。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Test
{
    public partial class Form1 : Form
    {
        private Point startPoint = new Point();
        private Point endPoint = new Point();
        private int mouseX = 0;
        private int mouseY = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseX = System.Windows.Forms.Cursor.Position.X;
                mouseY = System.Windows.Forms.Cursor.Position.Y;
                chart1.Invalidate();

            }
        }

        private void chart1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g1 = this.CreateGraphics();
            Pen linePen = new Pen(Color.Green, 1);
            Pen ellipsePen = new Pen(Color.Red, 1);
            startPoint = new Point(mouseX, mouseY);
            endPoint = new Point(mouseX, mouseY);
            g1.DrawLine(linePen, startPoint, endPoint);
            g1.DrawEllipse(ellipsePen, mouseX - 2, mouseY - 2, 4, 4);
            linePen.Dispose();
            ellipsePen.Dispose();
            g1.Dispose();
        }
    }
}

现在代码的方式,它绘制的点远远超出Chart控制区域。

1 个答案:

答案 0 :(得分:1)

那是因为你使用了错误的鼠标坐标。 替换这些行

mouseX = System.Windows.Forms.Cursor.Position.X;
mouseY = System.Windows.Forms.Cursor.Position.Y;

有了这个:

mouseX = e.X;
mouseY = e.Y;

System.Windows.Forms.Cursor.Position使用表单作为基础返回鼠标的坐标,而MouseEventArgs使用将事件作为基础引发的控件返回鼠标的坐标。