how to enable zooming in Microsoft chart control by using Mouse wheel

后端 未结 4 1374
长情又很酷
长情又很酷 2020-12-29 23:11

I am using Microsoft Chart control in my project and I want to enable zooming feature in Chart Control by using Mouse Wheel, how can I achieve this?

but user don\'t

4条回答
  •  忘掉有多难
    2020-12-29 23:32

    Waaaay late to the party, but I had this challenge myself today. I am sure the following can be improved, still, but it's what I came up with. I tested this with .net 4.5.2 and 4.6, so I am not sure if it works with older frameworks.

    I've combined a couple of answers from way in the past and made the following:

    using System;
    using System.Windows.Forms;
    using System.Windows.Forms.DataVisualization.Charting;
    
    namespace ExampleApp
    {
        public partial class Form1 : Form
        {
            private const float CZoomScale = 4f;
            private int FZoomLevel = 0;
    
            public Form1()
            {
                InitializeComponent();
                chart1.MouseWheel += Chart1_MouseWheel;
            }
    
            private void Chart1_MouseEnter(object sender, EventArgs e)
            {
                if (!chart1.Focused)
                    chart1.Focus();
            }
    
            private void Chart1_MouseLeave(object sender, EventArgs e)
            {
                if (chart1.Focused)
                    chart1.Parent.Focus();
            }
    
            private void Chart1_MouseWheel(object sender, MouseEventArgs e)
            {
                try {
                    Axis xAxis = chart1.ChartAreas[0].AxisX;
                    double xMin = xAxis.ScaleView.ViewMinimum;
                    double xMax = xAxis.ScaleView.ViewMaximum;
                    double xPixelPos = xAxis.PixelPositionToValue(e.Location.X);
    
                    if (e.Delta < 0 && FZoomLevel > 0) {
                        // Scrolled down, meaning zoom out
                        if (--FZoomLevel <= 0) {
                            FZoomLevel = 0;
                            xAxis.ScaleView.ZoomReset();
                        } else {
                            double xStartPos = Math.Max(xPixelPos - (xPixelPos - xMin) * CZoomScale, 0);
                            double xEndPos = Math.Min(xStartPos + (xMax - xMin) * CZoomScale, xAxis.Maximum);
                            xAxis.ScaleView.Zoom(xStartPos, xEndPos);
                        }
                    } else if (e.Delta > 0) {
                        // Scrolled up, meaning zoom in
                        double xStartPos = Math.Max(xPixelPos - (xPixelPos - xMin) / CZoomScale, 0);
                        double xEndPos = Math.Min(xStartPos + (xMax - xMin) / CZoomScale, xAxis.Maximum);
                        xAxis.ScaleView.Zoom(xStartPos, xEndPos);
                        FZoomLevel++;
                    }
                } catch { }
            }
        }
    }
    

提交回复
热议问题