Меню Рубрики

Chart для windows forms

Chart для windows forms

БлогNot. Chart, примеры в Studio

Chart, примеры в Studio

Компонента Chart (диаграмма) в Visual Studio довольно удобна, хотя для начинающих обычно сложно выбрать из множества её возможностей самые актуальные. К тому же, задокументировано-то всё лишь на MSDN.

Приведу несколько примеров, анализ которых поможет Вам быстро освоить основные приёмы работы с графиками и диаграммами в Visual C++. Все коды проверены в сборке Express 2010.

Пример 1. Добавим на форму компоненту Chart и выведем туда данные
Пример 2. Сделаем красивый Chart программно, можно по нажатию новой кнопки на той же форме
Пример 3. Вытащим данные из Chart в TextBox
Пример 4. Сделаем парсер выражений на основе чужого класса — это можно применить для создания полноценного «графопостроителя»

Добавим какой-нибудь не очень сложный парсер, например, класс parser.cpp от Chaos Master.

Кинем файлы parser.cpp и parser.h в папку с кодом (Имя_проекта/Имя_проекта, где находится Form1.h ). В меню скажем Проект — Существующий элемент и добавим файл .cpp (он д.б. в «Файлы исходного кода» Обозревателя решений)

Код выбранного нами парсера старый, так что нам придётся кое-что переделывать, например, строки char * в String ^ и обратно.

Добавим на форму компоненты textBox1 и label1 , напишем демо-код для применения парсера (вызывается по нажатию кнопки):

Возможно, понадобится изменить какие-то ещё мелочи, например, я в файле parser.cpp раскомментарил строку

и изменил в коде exp(1) на exp(1.) — иначе не компилировалось в Studio.

Также ясно, что в начале файла form1.h добавлена строка

Теперь в поле ввода можно писать любые допустимые парсером выражения с переменной x , например, cos(x)+1 , текущее значение переменной x из программы подставится в выражение и его результат динамически подсчитается.

На основе показанных кодов легко сделать, например, программу построения графиков с интерпретацией введённой пользователем функции. Скажем, если выражение для функции с аргументом, обозначенным x , вводится в текстовое поле textBox1 , код построения графика функции в пределах от 0 до 3.14 с шагом, равным 0.1 , будет таким:

P.S. В более новой Studio 2019 пришлось сделать ^f1 вместо f1 и, соответственно, везде f1-> вместо f1.

Заменить фиксированные пределы и шаг на вводимые из формы — элементарно. Вот что вышло для теста:

Пример 5. Применение разрывов

На форму проекта помещена chart1 со свойством Dock = Fill , построение происходит по загрузке формы.

04.02.2014, 17:03; рейтинг: 39338

Источник

Chart Class

Definition

Serves as the root class of the Chart control.

Remarks

This class exposes all of the properties, methods and events of the Chart Windows control.

Two important properties of the Chart class are the Series and ChartAreas properties, both of which are collection properties. The Series collection property stores Series objects, which are used to store data that is to be displayed, along with attributes of that data. The ChartAreas collection property stores ChartArea objects, which are primarily used to draw one or more charts using one set of axes.

Constructors

Initializes a new instance of the Chart class.

Properties

Gets the AccessibleObject assigned to the control.

Gets or sets the default action description of the control for use by accessibility client applications.

Gets or sets the description of the control used by accessibility client applications.

Gets or sets the name of the control used by accessibility client applications.

Gets or sets the accessible role of the control.

Gets or sets a value indicating whether the control can accept data that the user drags onto it.

Gets or sets the edges of the container to which a control is bound and determines how a control is resized with its parent.

Gets or sets a collection that stores the chart annotations.

Gets or sets a value that determines whether anti-aliasing is used when text and graphics are drawn.

Gets or sets where this control is scrolled to in ScrollControlIntoView(Control).

This property is not relevant for this class.

Gets or sets the background color of the Chart object.

Gets or sets the orientation for the background gradient of a Chart control. Also determines whether a gradient is used.

The BackgroundImage property is not used. Use the BackImage property instead.

Gets or sets the background image layout as defined in the ImageLayout enumeration.

Gets or sets the hatching style of the Chart control.

Gets or sets the background image of the Chart control.

Gets or sets the background image alignment used for the Unscaled drawing mode.

Gets or sets the color of the Chart control that will be displayed as transparent.

Gets or sets the drawing mode for the background image of the Chart control.

Gets or sets the secondary color of the chart background.

Gets or sets the BindingContext for the control.

Gets or sets the color of the chart border.

Gets or sets the style of the border.

Gets or sets the color of the border line.

Gets or sets the style of the border line.

Gets or sets the width of the border line.

Gets or sets a BorderSkin object, which provides border skin functionality for the Chart control.

Gets or set s the width of the chart border.

Gets the distance, in pixels, between the bottom edge of the control and the top edge of its container’s client area.

Gets or sets the size and location of the control including its nonclient elements, in pixels, relative to the parent control.

Gets the build number of the Chart control.

Gets a value indicating whether the ImeMode property can be set to an active value, to enable IME support.

Gets a value indicating whether the control can receive focus.

Determines if events can be raised on the control.

Gets a value indicating whether the control can be selected.

Gets or sets a value indicating whether the control has captured the mouse.

Gets or sets a value indicating whether the control causes validation to be performed on any controls that require validation when it receives focus.

Gets a read-only ChartAreaCollection object that is used to store ChartArea objects.

Gets the rectangle that represents the client area of the control.

Gets or sets the height and width of the client area of the control.

Gets the name of the company or creator of the application containing the control.

Gets the IContainer that contains the Component.

Gets a value indicating whether the control, or one of its child controls, currently has the input focus.

Gets or sets the shortcut menu associated with the control.

Gets or sets the ContextMenuStrip associated with this control.

Gets the collection of controls contained within the control.

Gets a value indicating whether the control has been created.

Gets the required creation parameters when the control handle is created.

Gets or sets the cursor that is displayed when the mouse pointer is over the control.

Gets the data bindings for the control.

Gets a DataManipulator object that provides methods and properties that handle data.

Gets or sets the data source for the Chart object.

Gets or sets the default cursor for the control.

Gets the default Input Method Editor (IME) mode supported by the control.

Gets the space, in pixels, that is specified by default between controls.

Gets the length and height, in pixels, that is specified as the default maximum size of a control.

Gets the length and height, in pixels, that is specified as the default minimum size of a control.

Gets the internal spacing, in pixels, of the contents of a control.

Gets the default control size.

Gets a value that indicates whether the Component is currently in design mode.

Gets the DPI value for the display device where the control is currently being displayed.

Gets the rectangle that represents the display area of the control.

Gets a value indicating whether the base Control class is in the process of disposing.

Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.

Gets or sets a value indicating whether the control can respond to user interaction.

Gets the list of event handlers that are attached to this Component.

Gets a value indicating whether the control has input focus.

Gets the font properties of the control.

Gets or sets the height of the font of the control.

Gets or sets the text color of the Chart control.

Gets the window handle that the control is bound to.

Gets a value indicating whether the control contains one or more child controls.

Gets or sets the height of the control.

Gets a NamedImagesCollection object that stores NamedImage objects for the chart.

Gets or sets the Input Method Editor (IME) mode of the control.

Gets or sets the IME mode of a control.

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.

Gets or sets a value indicating whether the control is visible to accessibility applications.

Gets a value indicating whether the control has been disposed of.

Gets a value indicating whether the control has a handle associated with it.

Gets a value indicating whether the control is mirrored.

Gets or sets a flag that determines if a smooth gradient is applied when shadows are drawn.

Gets a cached instance of the control’s layout engine.

Gets or sets the distance, in pixels, between the left edge of the control and the left edge of its container’s client area.

Gets or sets a LegendCollection that stores all Legend objects used by the Chart control.

Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container.

Gets or sets the space between controls.

Gets or sets the size that is the upper limit that GetPreferredSize(Size) can specify.

Gets or sets the size that is the lower limit that GetPreferredSize(Size) can specify.

Gets or sets the name of the control.

Gets or sets padding within the control.

Gets or sets the palette for the Chart control.

Gets or sets an array of custom palette colors.

Gets or sets the parent container of the control.

Gets the size of a rectangular area into which the control can fit.

Gets a read-only PrintingManager object used for printing a chart.

Gets the product name of the assembly containing the control.

Gets the version of the assembly containing the control.

Gets a value indicating whether the control is currently re-creating its handle.

Gets or sets the window region associated with the control.

Gets or sets the horizontal resolution of the Chart renderer.

Gets or sets the vertical resolution of the Chart renderer.

This property is now obsolete.

Gets or sets a value indicating whether the control redraws itself when resized.

Gets the distance, in pixels, between the right edge of the control and the left edge of its container’s client area.

Gets or sets a value indicating whether control’s elements are aligned to support locales using right-to-left fonts.

Gets a value that determines the scaling of child controls.

Gets a ChartSerializer object that is used for chart serialization.

Gets a SeriesCollection object, which contains Series objects.

Gets a value indicating whether the control should display focus rectangles.

Gets a value indicating whether the user interface is in the appropriate state to show or hide keyboard accelerators.

Gets or sets the site of the control.

Gets or sets the size of the Chart control.

Gets or sets a flag that determines whether non-critical exceptions should be suppressed.

Gets or sets the tab order of the control within its container.

Gets or sets a value indicating whether the user can give the focus to this control using the TAB key.

Gets or sets the object that contains data about the control.

Gets or sets the text associated with this control.

Gets or sets the TextAntiAliasingQuality type to use when applying anti-aliasing to text.

Gets or sets a TitleCollection object that is used to store all Title objects used by the Chart control.

Gets or sets the distance, in pixels, between the top edge of the control and the top edge of its container’s client area.

Gets the parent control that is not parented by another Windows Forms control. Typically, this is the outermost Form that the control is contained in.

Gets or sets a value indicating whether to use the wait cursor for the current control and all child controls.

Gets or sets a value indicating whether the control and all its child controls are displayed.

Gets or sets the width of the control.

This property is not relevant for this class.

Methods

Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control.

Notifies the accessibility client applications of the specified AccessibleEvents for the specified child control .

Aligns data points along the X axis using their axis labels. Applicable when multiple series are indexed and their X-values are strings.

Aligns data points using their axis labels. All series in the chart are aligned, using the specified sort order.

Aligns data points from different series along the X axis using their axis labels. The specified series in the chart are aligned using an ascending sort order.

Aligns data points using their axis labels.

Sets the automatically assigned series and data point colors, to allow programmatic access at run time.

Signals to the object that initialization is starting.

Executes the specified delegate asynchronously on the thread that the control’s underlying handle was created on.

Executes the specified delegate asynchronously with the specified arguments, on the thread that the control’s underlying handle was created on.

Brings the control to the front of the z-order.

Retrieves a value indicating whether the specified control is a child of the control.

When overridden in a derived class, returns the custom AccessibleObject for the entire chart.

Forces the creation of the visible control, including the creation of the handle and any visible child controls.

Creates a new instance of the control collection for the control.

Creates the Graphics for the control.

Creates a handle for the control.

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

Data binds the Chart control to a data source.

Data binds a chart to the table, with one series created per unique value in a given column.

Data binds a chart to the table, with one series created per unique value in a given column.

Automatically creates and binds series data to the specified data table.

Automatically creates and binds series data to the specified data table, and optionally populates X-values.

Sends the specified message to the default window procedure.

Destroys the handle associated with the control.

Releases all resources used by the Component.

Releases unmanaged and, optionally, managed resources.

Begins a drag-and-drop operation.

Supports rendering to the specified bitmap.

Signals to the Chart object that initialization is complete.

Retrieves the return value of the asynchronous operation represented by the IAsyncResult passed.

Determines whether the specified object is equal to the current object.

Retrieves the form that the control is on.

Sets input focus to the control.

Retrieves the specified AccessibleObject.

Retrieves a value indicating how a control will behave when its AutoSize property is enabled.

Returns the chart element outline.

Retrieves the child control that is located at the specified coordinates.

Retrieves the child control that is located at the specified coordinates, specifying whether to ignore child controls of a certain type.

Returns the next ContainerControl up the control’s chain of parent controls.

Serves as the default hash function.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

Retrieves the next control forward or back in the tab order of child controls.

Retrieves the size of a rectangular area into which a control can be fitted.

Retrieves the bounds within which the control is scaled.

Returns the requested chart service.

Retrieves the value of the specified control style bit for the control.

Determines if the control is a top-level control.

Gets the Type of the current instance.

Conceals the control from the user.

Determines the chart element, if any, that is located at a point defined by the given X and Y coordinates.

Determines the chart element, if any, that is located at a point defined by given X and Y coordinates. Transparent elements can optionally be ignored.

Determines whether a chart element that is one of the specified types is located at a point defined by the given X and Y coordinates.

Determines if a chart element of a given type is located at a point defined by given X and Y coordinates.

Obtains a lifetime service object to control the lifetime policy for this instance.

Called after the control has been added to another container.

Invalidates the entire surface of the Chart and causes the Chart control to be redrawn.

Invalidates a specific region of the control and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.

Invalidates the specified area of the Chart control.

Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.

Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control.

Invalidates the specified region of the control (adds it to the control’s update region, which is the area that will be repainted at the next paint operation), and causes a paint message to be sent to the control. Optionally, invalidates the child controls assigned to the control.

Executes the specified delegate on the thread that owns the control’s underlying window handle.

Executes the specified delegate, on the thread that owns the control’s underlying window handle, with the specified list of arguments.

Raises the GotFocus event for the specified control.

Raises the LostFocus event for the specified control.

Raises the Click event for the specified control.

Raises the Paint event for the specified control.

Raises the PaintBackground event for the specified control.

Determines if a character is an input character that the control recognizes.

Determines whether the specified key is a regular input key or a special key that requires preprocessing.

Loads a template into the Chart control from an image stream.

Loads a template with the specified filename from the disk.

Converts a Logical DPI value to its equivalent DeviceUnit DPI value.

Transforms a size from logical to device units by scaling it for the current DPI and rounding down to the nearest integer value for width and height.

Creates a shallow copy of the current Object.

Creates a shallow copy of the current MarshalByRefObject object.

Raises the Invalidated event with a specified region of the control to invalidate.

Notifies the control of Windows messages.

Raises the BackColorChanged event when the BackColor property value of the control’s container changes.

Raises the BackgroundImageChanged event when the BackgroundImage property value of the control’s container changes.

Raises the BindingContextChanged event when the BindingContext property value of the control’s container changes.

Raises the EnabledChanged event when the Enabled property value of the control’s container changes.

Raises the FontChanged event when the Font property value of the control’s container changes.

Raises the ForeColorChanged event when the ForeColor property value of the control’s container changes.

Raises the RightToLeftChanged event when the RightToLeft property value of the control’s container changes.

Raises the VisibleChanged event when the Visible property value of the control’s container changes.

Forces the control to apply layout logic to all its child controls.

Forces the control to apply layout logic to all its child controls.

Computes the location of the specified screen point into client coordinates.

Computes the location of the specified client point into screen coordinates.

Preprocesses keyboard or input messages within the message loop before they are dispatched.

Preprocesses keyboard or input messages within the message loop before they are dispatched.

Processes a command key.

Processes a dialog character.

Processes a dialog key.

Processes a key message and generates the appropriate control events.

Processes a keyboard message.

Previews a keyboard message.

Processes a mnemonic character.

Raises the appropriate drag event.

Raises the appropriate key event.

Raises the appropriate mouse event.

Raises the appropriate paint event.

Forces the re-creation of the handle for the control.

Computes the size and location of the specified screen rectangle in client coordinates.

Computes the size and location of the specified client rectangle in screen coordinates.

Forces the control to invalidate its client area and immediately redraw itself and any child controls.

Provides constants for rescaling the control when a DPI change occurs.

Resets automatically calculated chart property values to «Auto».

Resets the BackColor property to its default value.

Causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.

Resets the Cursor property to its default value.

Resets the Font property to its default value.

Resets the ForeColor property to its default value.

Resets the ImeMode property to its default value.

Resets the control to handle the MouseLeave event.

Resets the RightToLeft property to its default value.

Resets the Text property to its default value (Empty).

Resumes usual layout logic.

Resumes usual layout logic, optionally forcing an immediate layout of pending layout requests.

Converts the specified ContentAlignment to the appropriate ContentAlignment to support right-to-left text.

Converts the specified HorizontalAlignment to the appropriate HorizontalAlignment to support right-to-left text.

Converts the specified LeftRightAlignment to the appropriate LeftRightAlignment to support right-to-left text.

Converts the specified ContentAlignment to the appropriate ContentAlignment to support right-to-left text.

Converts the specified HorizontalAlignment to the appropriate HorizontalAlignment to support right-to-left text.

Converts the specified LeftRightAlignment to the appropriate LeftRightAlignment to support right-to-left text.

Saves the chart image to the specified stream.

Saves the image to the specified stream.

Saves the chart image to the specified file.

Saves an image to the specified file.

Scales the control and any child controls.

Scales the entire control and any child controls.

Scales the control and all child controls by the specified scaling factor.

Scales a logical bitmap value to it’s equivalent device unit value when a DPI change occurs.

Scales a control’s location, size, padding and margin.

This method is not relevant for this class.

Activates the control.

Activates a child control. Optionally specifies the direction in the tab order to select the control from.

Activates the next control.

Sends the control to the back of the z-order.

Sets a value indicating how a control will behave when its AutoSize property is enabled.

Sets the bounds of the control to the specified location and size.

Sets the specified bounds of the control to the specified location and size.

Performs the work of setting the specified bounds of this control.

Sets the size of the client area of the control.

Sets a specified ControlStyles flag to either true or false .

Sets the control as the top-level control.

Sets the control to the specified visible state.

Displays the control to the user.

Determines the size of the entire control from the height and width of its client area.

Temporarily suspends the layout logic for the control.

Returns a String containing the name of the Component, if any. This method should not be overridden.

Causes the control to redraw the invalidated regions within its client area.

Updates the annotations in the Chart control.

Updates the bounds of the control with the current size and location.

Updates the bounds of the control with the specified size and location.

Updates the bounds of the control with the specified size, location, and client size.

Updates the cursor in the Chart control.

Forces the assigned styles to be reapplied to the control.

Updates the control in its parent’s z-order.

Processes Windows messages.

Events

Occurs when the end-user places an annotation on the chart.

Occurs when the annotation position is changed.

Occurs when the annotation position is about to change.

Occurs when a selection of the annotation is changed.

Occurs when the annotation text is changed.

This event is not relevant for this class.

Occurs when the axis scroll bar is clicked by the end-user.

Occurs when the axis scale view position or size is changed.

Occurs when the axis scale view position or size is about to change.

Occurs when the value of the BackColor property changes.

Occurs when the value of the BackgroundImage property changes.

Occurs when the BackgroundImageLayout property changes.

Occurs when the value of the BindingContext property changes.

Occurs when the value of the CausesValidation property changes.

Occurs when the focus or keyboard user interface (UI) cues change.

Occurs when the control is clicked.

Occurs when the value of the ClientSize property changes.

Occurs when the value of the ContextMenu property changes.

Occurs when the value of the ContextMenuStrip property changes.

Occurs when a new control is added to the Control.ControlCollection.

Occurs when a control is removed from the Control.ControlCollection.

Occurs when the value of the Cursor property changes.

Occurs when the cursor position is changed.

Occurs when the cursor position is about to change.

Occurs just before the chart image is drawn. Use this event to customize the chart picture.

Occurs when the chart legend must be customized.

Occurs when the component is disposed by a call to the Dispose() method.

Occurs when the value of the Dock property changes.

Occurs when the control is double-clicked.

Occurs when the DPI setting for a control is changed programmatically after the DPI of its parent control or form has changed.

Occurs when the DPI setting for a control is changed programmatically before a DPI change event for its parent control or form has occurred.

Occurs when a drag-and-drop operation is completed.

Occurs when an object is dragged into the control’s bounds.

Occurs when an object is dragged out of the control’s bounds.

Occurs when an object is dragged over the control’s bounds.

Occurs when the Enabled property value has changed.

Occurs when the control is entered.

Occurs when the Font property value changes.

Occurs when the ForeColor property value changes.

Occurs when a numeric value has to be converted to a string.

Occurs before showing the tooltip to get the tooltip text.

Occurs during a drag operation.

Occurs when the control receives focus.

Occurs when a handle is created for the control.

Occurs when the control’s handle is in the process of being destroyed.

Occurs when the user requests help for a control.

Occurs when the ImeMode property has changed.

Occurs when a control’s display requires redrawing.

Occurs when a key is pressed while the control has focus.

Occurs when a character. space or backspace key is pressed while the control has focus.

Occurs when a key is released while the control has focus.

Occurs when a control should reposition its child controls.

Occurs when the input focus leaves the control.

Occurs when the Location property value has changed.

Occurs when the control loses focus.

Occurs when the control’s margin changes.

Occurs when the control loses mouse capture.

Occurs when the control is clicked by the mouse.

Occurs when the control is double clicked by the mouse.

Occurs when the mouse pointer is over the control and a mouse button is pressed.

Occurs when the mouse pointer enters the control.

Occurs when the mouse pointer rests on the control.

Occurs when the mouse pointer leaves the control.

Occurs when the mouse pointer is moved over the control.

Occurs when the mouse pointer is over the control and a mouse button is released.

Occurs when the mouse wheel moves while the control has focus.

Occurs when the control is moved.

Occurs when the control’s padding changes.

Occurs when the control is redrawn.

Occurs when the Parent property value changes.

Occurs when the chart element is painted.

Occurs when the chart element background is painted.

Occurs before the KeyDown event when a key is pressed while focus is on this control.

Occurs when AccessibleObject is providing help to accessibility applications.

Occurs during a drag-and-drop operation and enables the drag source to determine whether the drag-and-drop operation should be canceled.

Occurs when the value of the Region property changes.

Occurs when the control is resized.

Occurs when the RightToLeft property value changes.

Occurs when the selection start position or end position is changed.

Occurs when the selection start or end position is about to change.

Occurs when the Size property value changes.

Occurs when the control style changes.

Occurs when the system colors change.

Occurs when the TabIndex property value changes.

Occurs when the TabStop property value changes.

Occurs when the Text property value changes.

Occurs when the control is finished validating.

Occurs when the control is validating.

Occurs when the Visible property value changes.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Charset windows 1251 что это
  • Charset windows 1251 не работает
  • Charset windows 1251 nginx
  • Charms bar для windows 10
  • Charlie программа для windows