Back to Devexpress

Customize the Crosshair Cursor at Runtime

windowsforms-404561-controls-and-libraries-chart-control-end-user-features-tooltip-and-crosshair-cursor-customize-crosshair-cursor-at-runtime.md

latest22.3 KB
Original Source

Customize the Crosshair Cursor at Runtime

  • Sep 22, 2023
  • 9 minutes to read

The Chart Control’s Crosshair Cursor API contains the ChartControl.CustomDrawCrosshair event in whose handler the Crosshair Cursor’s elements can be customized individually:

Event parameters include:

e.CrosshairAxisLabelElementsGets the settings of crosshair axis label elements to customize their appearance.e.CrosshairElementGroupsProvides access to the settings of crosshair elements and crosshair group header elements to customize their appearance.e.CrosshairLegendElementsReturns crosshair legend elements to customize their appearance.e.CrosshairLineElementGets the settings of a crosshair line element to customize its appearance (color, line style).e.IndicatorLegendElementsReturns all indicator elements that the Crosshair Cursor shows in a legend.

Customize the Crosshair Element’s Appearance

This example shows how to use the ChartControl.CustomDrawCrosshair event to create a custom appearance for the crosshair cursor. This event is invoked when you select the Custom Draw Crosshair Cursor checkbox.

View Example

cs
using System;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.Drawing;
using DevExpress.XtraCharts;

namespace CustomDrawCrosshairCursor {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        private void OnCheckEditCheckedChanged(object sender, EventArgs e) {
            if (checkEdit1.Checked)
                chartControl1.CustomDrawCrosshair += OnChartControlCustomDrawCrosshair;
            else 
                chartControl1.CustomDrawCrosshair -= OnChartControlCustomDrawCrosshair;               
        }

        private void OnChartControlCustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e) {
            // Specify the crosshair argument line color, dash style and thickness.
            e.CrosshairLineElement.Color = Color.Green;
            e.CrosshairLineElement.LineStyle.DashStyle = DashStyle.DashDot;
            e.CrosshairLineElement.LineStyle.Thickness = 3;

            // Specify the back color for the crosshair argument axis label. 
            foreach (CrosshairAxisLabelElement axisLabelElement in e.CrosshairAxisLabelElements)
                axisLabelElement.BackColor = Color.Blue;

            foreach (CrosshairElementGroup group in e.CrosshairElementGroups) {
                CrosshairGroupHeaderElement groupHeaderElement = group.HeaderElement;

                // Specify the text, text color and font for the crosshair group header element. 
                groupHeaderElement.Text = "Custom draw";
                groupHeaderElement.TextColor = Color.Green;
                groupHeaderElement.DXFont = new DXFont("SegoeUI", 12, DXFontStyle.Bold);

                // Obtain the first series.
                CrosshairElement element = group.CrosshairElements[0];

                // Specify the color, dash style and thickness for the crosshair value lines. 
                element.LineElement.Color = Color.DarkViolet;
                element.LineElement.LineStyle.DashStyle = DashStyle.Dash;
                element.LineElement.LineStyle.Thickness = 2;

                // Specify the text color and back color for the crosshair value labels.
                element.AxisLabelElement.TextColor = Color.Red;
                element.AxisLabelElement.BackColor = Color.Yellow;

                // Format the text shown for the series in the crosshair cursor label. Specify the text color and marker size. 
                element.LabelElement.TextColor = Color.Red;
                element.LabelElement.MarkerSize = new Size(15, 15);
                element.LabelElement.Text = string.Format("{0}: A={1}; V={2}", element.Series.Name, element.SeriesPoint.Argument, element.SeriesPoint.Values[0]);
            }
        }
    }
}
vb
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports DevExpress.Drawing
Imports DevExpress.XtraCharts

Namespace CustomDrawCrosshairCursor

    Public Partial Class Form1
        Inherits Form

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub OnCheckEditCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
            If checkEdit1.Checked Then
                AddHandler chartControl1.CustomDrawCrosshair, AddressOf OnChartControlCustomDrawCrosshair
            Else
                RemoveHandler chartControl1.CustomDrawCrosshair, AddressOf OnChartControlCustomDrawCrosshair
            End If
        End Sub

        Private Sub OnChartControlCustomDrawCrosshair(ByVal sender As Object, ByVal e As CustomDrawCrosshairEventArgs)
            ' Specify the crosshair argument line color, dash style and thickness.
            e.CrosshairLineElement.Color = Color.Green
            e.CrosshairLineElement.LineStyle.DashStyle = DashStyle.DashDot
            e.CrosshairLineElement.LineStyle.Thickness = 3
            ' Specify the back color for the crosshair argument axis label. 
            For Each axisLabelElement As CrosshairAxisLabelElement In e.CrosshairAxisLabelElements
                axisLabelElement.BackColor = Color.Blue
            Next

            For Each group As CrosshairElementGroup In e.CrosshairElementGroups
                Dim groupHeaderElement As CrosshairGroupHeaderElement = group.HeaderElement
                ' Specify the text, text color and font for the crosshair group header element. 
                groupHeaderElement.Text = "Custom draw"
                groupHeaderElement.TextColor = Color.Green
                groupHeaderElement.DXFont = New DXFont("SegoeUI", 12, DXFontStyle.Bold)
                ' Obtain the first series.
                Dim element As CrosshairElement = group.CrosshairElements(0)
                ' Specify the color, dash style and thickness for the crosshair value lines. 
                element.LineElement.Color = Color.DarkViolet
                element.LineElement.LineStyle.DashStyle = DashStyle.Dash
                element.LineElement.LineStyle.Thickness = 2
                ' Specify the text color and back color for the crosshair value labels.
                element.AxisLabelElement.TextColor = Color.Red
                element.AxisLabelElement.BackColor = Color.Yellow
                ' Format the text shown for the series in the crosshair cursor label. Specify the text color and marker size. 
                element.LabelElement.TextColor = Color.Red
                element.LabelElement.MarkerSize = New Size(15, 15)
                element.LabelElement.Text = String.Format("{0}: A={1}; V={2}", element.Series.Name, element.SeriesPoint.Argument, element.SeriesPoint.Values(0))
            Next
        End Sub
    End Class
End Namespace

Disable Crosshair Snap Mode

The example below displays the Crosshair Cursor for the current/previous point until the cursor reaches the next point in the series. Handle the ChartControl.CustomDrawCrosshair event to change the text of a displayed crosshair label.

cs
private void Form1_Load(object sender, EventArgs e) {
    // Create a chart.
    ChartControl chart = new ChartControl();
    chart.CustomDrawCrosshair += Chart_CustomDrawCrosshair;
}

private void Chart_CustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e) {
    var chart = (ChartControl)sender;
    var diagram = (XYDiagram)chart.Diagram;
    // Get diagram coordinates
    var coords = diagram.PointToDiagram(chart.PointToClient(Cursor.Position));
    // Get the current argument. Use the DateTimeArgument property if your scale is DateTime
    var currentArgumentValue = coords.DateTimeArgument;

    this.Text = currentArgumentValue.ToString();

    var series = chart.Series[0];
    // Find previous point in the series:
    var previousPoint = series.Points
        .OrderBy(p => ((SeriesPoint)p).DateTimeArgument)
        .LastOrDefault(p => ((SeriesPoint)p).DateTimeArgument <= currentArgumentValue) as SeriesPoint;

    if (previousPoint != null)
        foreach (CrosshairElementGroup group in e.CrosshairElementGroups) {
            CrosshairGroupHeaderElement groupHeaderElement = group.HeaderElement;
            CrosshairElement element = group.CrosshairElements[0];
            // Change the label's text. Use the DateTimeArgument property if your scale is DateTime
            element.LabelElement.Text = string.Format("Argument: {0}, Value: {1}", previousPoint.DateTimeArgument, previousPoint.Values[0]);
        }
}
vb
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    ' Create a chart.
    Dim chart As New ChartControl()
    AddHandler chart.CustomDrawCrosshair, AddressOf Chart_CustomDrawCrosshair
End Sub

Private Sub Chart_CustomDrawCrosshair(ByVal sender As Object, ByVal e As CustomDrawCrosshairEventArgs)
    Dim chart = DirectCast(sender, ChartControl)
    Dim diagram = CType(chart.Diagram, XYDiagram)
    ' Get diagram coordinates
    Dim coords = diagram.PointToDiagram(chart.PointToClient(Cursor.Position))
    ' Get the current argument. Use the DateTimeArgument property if your scale is DateTime
    Dim currentArgumentValue = coords.DateTimeArgument

    Me.Text = currentArgumentValue.ToString()

    Dim series = chart.Series(0)
    ' Find previous point in the series:
    Dim previousPoint = TryCast(series.Points.OrderBy(Function(p) CType(p, SeriesPoint).DateTimeArgument).LastOrDefault(Function(p) CType(p, SeriesPoint).DateTimeArgument <= currentArgumentValue), SeriesPoint)

    If previousPoint IsNot Nothing Then
        For Each group As CrosshairElementGroup In e.CrosshairElementGroups
            Dim groupHeaderElement As CrosshairGroupHeaderElement = group.HeaderElement
            Dim element As CrosshairElement = group.CrosshairElements(0)
            ' Change the label's text. Use the DateTimeArgument property if your scale is DateTime
            element.LabelElement.Text = String.Format("Argument: {0}, Value: {1}", previousPoint.DateTimeArgument, previousPoint.Values(0))
        Next group
    End If
End Sub

Hide a Marker in the Crosshair Label

The example below shows how to hide a marker in the Crosshair Cursor Label.

csharp
private void stockChart_CustomDrawCrosshair(object sender, DevExpress.XtraCharts.CustomDrawCrosshairEventArgs e) {
        foreach (CrosshairElementGroup g in e.CrosshairElementGroups) {
            foreach (CrosshairElement el in g.CrosshairElements)
                el.LabelElement.MarkerVisible = false;
        }
}
vb
Private Sub stockChart_CustomDrawCrosshair(ByVal sender As Object, ByVal e As DevExpress.XtraCharts.CustomDrawCrosshairEventArgs)
        For Each g As CrosshairElementGroup In e.CrosshairElementGroups
            For Each el As CrosshairElement In g.CrosshairElements
                el.LabelElement.MarkerVisible = False
            Next el
        Next g
End Sub

Draw a Custom Series Marker in the Crosshair

This example demonstrates how to use the ChartControl.CustomDrawCrosshair event to modify the legend markers of bar series.

View Example

To access crosshair element groups, use the CustomDrawCrosshairEventArgs.CrosshairElementGroups property. Elements are separated into several groups when crosshair labels are displayed for each pane.

Use the following properties to access crosshair elements and customize them:

CrosshairElementGroup.HeaderElementGets the settings of crosshair group header elements to customize their appearance.CrosshairElementGroup.CrosshairElementsGets the settings of crosshair elements (crosshair value lines, crosshair value labels, crosshair labels) to customize their appearance.CrosshairElementBase.LabelElementReturns the Crosshair Cursor‘s label element to change its settings when using the ChartControl.CustomDrawCrosshair event to modify the Crosshair’s appearance.CrosshairElementBase.AxisLabelElementReturns the Crosshair Cursor‘s axis label element to change its settings when using the ChartControl.CustomDrawCrosshair event to modify the Crosshair’s appearance.CrosshairLabelElement.DXMarkerImageSpecifies the marker image of a crosshair cursor label when implementing custom draw in the crosshair cursor.

cs
using CustomDrawCrosshairSample.Model;
using DevExpress.Drawing;
using DevExpress.XtraCharts;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;

namespace CustomDrawCrosshairSample {
    public partial class Form1 : DevExpress.XtraEditors.XtraForm {
        Dictionary<string, DXImage> photoCache = new Dictionary<string, DXImage>();
        Dictionary<string, DXBitmap> bitmapCache = new Dictionary<string, DXBitmap>();
        #region #Constants
        const int borderSize = 2;
        const int scaledPhotoWidth = 32;
        const int scaledPhotoHeight = 34;
        // Width and height of scaled photo with border.
        const int totalWidth = 36;
        const int totalHeight = 38;

        // Rects required to create a custom legend series marker.
        static readonly Rectangle photoRect = new Rectangle(
                borderSize, borderSize,
                scaledPhotoWidth, scaledPhotoHeight);
        static readonly Rectangle totalRect = new Rectangle(
                0, 0,
                totalWidth, totalHeight);
        #endregion

        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            using (var context = new NwindDbContext()) {
                InitPhotoCache(context.Employees);
                chart.DataSource = context.Orders.ToList();
            }

            chart.SeriesDataMember = "Employee.FullName";
            chart.SeriesTemplate.ArgumentDataMember = "OrderDate";
            chart.SeriesTemplate.ValueDataMembers.AddRange("Freight");

            XYDiagram diagram = chart.Diagram as XYDiagram;
            if (diagram != null) {
                diagram.AxisX.DateTimeScaleOptions.AggregateFunction = AggregateFunction.Sum;
                diagram.AxisX.DateTimeScaleOptions.MeasureUnit = DateTimeMeasureUnit.Year;
            }

            chart.CustomDrawCrosshair += OnCustomDrawCrosshair;
        }

        void InitPhotoCache(IEnumerable<Employee> employees) {
            photoCache.Clear();
            foreach (var employee in employees) {
                using (MemoryStream stream = new MemoryStream(employee.Photo)) {
                    if (!photoCache.ContainsKey(employee.FullName))
                        photoCache.Add(employee.FullName, DXImage.FromStream(stream));
                }
            }
        }

        #region #CustomDrawCrosshairHandler
        private void OnCustomDrawCrosshair(object sender, CustomDrawCrosshairEventArgs e) {
            foreach (CrosshairElementGroup group in e.CrosshairElementGroups) {
                if (group.CrosshairElements[0] != null)
                    group.HeaderElement.Text = String.Format("Sales in {0:yyyy}", group.CrosshairElements[0].SeriesPoint.DateTimeArgument);
                foreach (CrosshairElement element in group.CrosshairElements) {
                    DXBitmap image;
                    if (!bitmapCache.TryGetValue(element.Series.Name, out image)) {
                        image = new DXBitmap(totalWidth, totalHeight);
                        using (DXGraphics graphics = DXGraphics.FromImage(image)) {
                            using (DXSolidBrush brush = new DXSolidBrush(element.LabelElement.MarkerColor)) {
                                graphics.FillRectangle(brush, totalRect);
                            }
                            DXImage photo;
                            if (photoCache.TryGetValue(element.Series.Name, out photo))
                                graphics.DrawImage(photo, photoRect);
                        }
                        bitmapCache.Add(element.Series.Name, image);
                    }
                    element.LabelElement.DXMarkerImage = image;
                    element.LabelElement.MarkerSize = new Size(totalWidth, totalHeight);
                }
            }
        }
        #endregion 
    }
}
vb
Imports CustomDrawCrosshairSample.Model
Imports DevExpress.Drawing
Imports DevExpress.XtraCharts
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.IO
Imports System.Linq

Namespace CustomDrawCrosshairSample

    Public Partial Class Form1
        Inherits DevExpress.XtraEditors.XtraForm

        Private photoCache As Dictionary(Of String, DXImage) = New Dictionary(Of String, DXImage)()

        Private bitmapCache As Dictionary(Of String, DXBitmap) = New Dictionary(Of String, DXBitmap)()

#Region "#Constants"
        Const borderSize As Integer = 2

        Const scaledPhotoWidth As Integer = 32

        Const scaledPhotoHeight As Integer = 34

        ' Width and height of scaled photo with border.
        Const totalWidth As Integer = 36

        Const totalHeight As Integer = 38

        ' Rects required to create a custom legend series marker.
        Private Shared ReadOnly photoRect As Rectangle = New Rectangle(borderSize, borderSize, scaledPhotoWidth, scaledPhotoHeight)

        Private Shared ReadOnly totalRect As Rectangle = New Rectangle(0, 0, totalWidth, totalHeight)

#End Region
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            Using context = New NwindDbContext()
                InitPhotoCache(context.Employees)
                chart.DataSource = context.Orders.ToList()
            End Using

            chart.SeriesDataMember = "Employee.FullName"
            chart.SeriesTemplate.ArgumentDataMember = "OrderDate"
            chart.SeriesTemplate.ValueDataMembers.AddRange("Freight")
            Dim diagram As XYDiagram = TryCast(chart.Diagram, XYDiagram)
            If diagram IsNot Nothing Then
                diagram.AxisX.DateTimeScaleOptions.AggregateFunction = AggregateFunction.Sum
                diagram.AxisX.DateTimeScaleOptions.MeasureUnit = DateTimeMeasureUnit.Year
            End If

            AddHandler chart.CustomDrawCrosshair, AddressOf OnCustomDrawCrosshair
        End Sub

        Private Sub InitPhotoCache(ByVal employees As IEnumerable(Of Employee))
            photoCache.Clear()
            For Each employee In employees
                Using stream As MemoryStream = New MemoryStream(employee.Photo)
                    If Not photoCache.ContainsKey(employee.FullName) Then photoCache.Add(employee.FullName, DXImage.FromStream(stream))
                End Using
            Next
        End Sub

#Region "#CustomDrawCrosshairHandler"
        Private Sub OnCustomDrawCrosshair(ByVal sender As Object, ByVal e As CustomDrawCrosshairEventArgs)
            For Each group As CrosshairElementGroup In e.CrosshairElementGroups
                If group.CrosshairElements(0) IsNot Nothing Then group.HeaderElement.Text = String.Format("Sales in {0:yyyy}", group.CrosshairElements(0).SeriesPoint.DateTimeArgument)
                For Each element As CrosshairElement In group.CrosshairElements
                    Dim image As DXBitmap
                    If Not bitmapCache.TryGetValue(element.Series.Name, image) Then
                        image = New DXBitmap(totalWidth, totalHeight)
                        Using graphics As DXGraphics = DXGraphics.FromImage(image)
                            Using brush As DXSolidBrush = New DXSolidBrush(element.LabelElement.MarkerColor)
                                graphics.FillRectangle(brush, totalRect)
                            End Using

                            Dim photo As DXImage
                            If photoCache.TryGetValue(element.Series.Name, photo) Then graphics.DrawImage(photo, photoRect)
                        End Using

                        bitmapCache.Add(element.Series.Name, image)
                    End If

                    element.LabelElement.DXMarkerImage = image
                    element.LabelElement.MarkerSize = New Size(totalWidth, totalHeight)
                Next
            Next
        End Sub
#End Region
    End Class
End Namespace

See Also

Crosshair Cursor