System windows forms mousebuttons

How Mouse Input Works in Windows Forms

Receiving and handling mouse input is an important part of every Windows application. You can handle mouse events to perform an action in your application, or use mouse location information to perform hit testing or other actions. In addition, you can change the way the controls in your application handle mouse input. This topic describes these mouse events in detail, and how to obtain and change system settings for the mouse. For more information about the data provided with the mouse events and the order in which the mouse click events are raised, see Mouse Events in Windows Forms.

Mouse Location and Hit-Testing

When the user moves the mouse, the operating system moves the mouse pointer. The mouse pointer contains a single pixel, called the hot spot, which the operating system tracks and recognizes as the position of the pointer. When the user moves the mouse or presses a mouse button, the Control that contains the HotSpot raises the appropriate mouse event. You can obtain the current mouse position with the Location property of the MouseEventArgs when handling a mouse event or by using the Position property of the Cursor class. You can subsequently use mouse location information to perform hit-testing, and then perform an action based on the location of the mouse. Hit-testing capability is built in to several controls in Windows Forms such as the ListView, TreeView, MonthCalendar and DataGridView controls. Used with the appropriate mouse event, MouseHover for example, hit-testing is very useful for determining when your application should perform a specific action.

Mouse Events

The primary way to respond to mouse input is to handle mouse events. The following table shows the mouse events and describes when they are raised.

Mouse Event Description
Click This event occurs when the mouse button is released, typically before the MouseUp event. The handler for this event receives an argument of type EventArgs. Handle this event when you only need to determine when a click occurs.
MouseClick This event occurs when the user clicks the control with the mouse. The handler for this event receives an argument of type MouseEventArgs. Handle this event when you need to get information about the mouse when a click occurs.
DoubleClick This event occurs when the control is double-clicked. The handler for this event receives an argument of type EventArgs. Handle this event when you only need to determine when a double-click occurs.
MouseDoubleClick This event occurs when the user double-clicks the control with the mouse. The handler for this event receives an argument of type MouseEventArgs. Handle this event when you need to get information about the mouse when a double-click occurs.
MouseDown This event occurs when the mouse pointer is over the control and the user presses a mouse button. The handler for this event receives an argument of type MouseEventArgs.
MouseEnter This event occurs when the mouse pointer enters the border or client area of the control, depending on the type of control. The handler for this event receives an argument of type EventArgs.
MouseHover This event occurs when the mouse pointer stops and rests over the control. The handler for this event receives an argument of type EventArgs.
MouseLeave This event occurs when the mouse pointer leaves the border or client area of the control, depending on the type of the control. The handler for this event receives an argument of type EventArgs.
MouseMove This event occurs when the mouse pointer moves while it is over a control. The handler for this event receives an argument of type MouseEventArgs.
MouseUp This event occurs when the mouse pointer is over the control and the user releases a mouse button. The handler for this event receives an argument of type MouseEventArgs.
MouseWheel This event occurs when the user rotates the mouse wheel while the control has focus. The handler for this event receives an argument of type MouseEventArgs. You can use the Delta property of MouseEventArgs to determine how far the mouse has scrolled.

Changing Mouse Input and Detecting System Settings

You can detect and change the way a control handles mouse input by deriving from the control and using the GetStyle and SetStyle methods. The SetStyle method takes a bitwise combination of ControlStyles values to determine whether the control will have standard click or double-click behavior or if the control will handle its own mouse processing. In addition, the SystemInformation class includes properties that describe the capabilities of the mouse and specify how the mouse interacts with the operating system. The following table summarizes these properties.

Mouse Buttons Перечисление

Определение

Задает константы, определяющие, какая кнопка мыши была нажата. Specifies constants that define which mouse button was pressed.

Это перечисление имеет атрибут FlagsAttribute, который разрешает побитовое сочетание значений его элементов.

Была нажата левая кнопка мыши. The left mouse button was pressed.

Была нажата средняя кнопка мыши. The middle mouse button was pressed.

Никакая кнопка мыши не была нажата. No mouse button was pressed.

Была нажата правая кнопка мыши. The right mouse button was pressed.

Была нажата первая кнопка XButton (XBUTTON1) на Microsoft IntelliMouse Explorer. The first XButton (XBUTTON1) on Microsoft IntelliMouse Explorer was pressed.

Была нажата вторая кнопка XButton (XBUTTON2) на Microsoft IntelliMouse Explorer. The second XButton (XBUTTON2) on Microsoft IntelliMouse Explorer was pressed.

Примеры

В следующем примере показано, как использовать GetCharFromPosition метод для получения символа из содержимого RichTextBox заданных координат элемента управления. The following example demonstrates how to use the GetCharFromPosition method to obtain a character from the contents of a RichTextBox given its control coordinates. В примере кода используются координаты, расположенные в MouseEventArgs объекте, переданном в качестве параметра обработчику событий, чтобы определить место в элементе управления для получения символа. The example code uses coordinates located in the MouseEventArgs object passed as a parameter to the event handler to determine the location in the control to obtain the character. Затем символ отображается в, MessageBox если он не является пробелом. The character is then displayed in a MessageBox if it is not a space character. В этом примере предполагается, что RichTextBox элемент управления с именем был richTextBox1 создан и что пример кода подключен к MouseDown событию RichTextBox . This example assumes that a RichTextBox control named richTextBox1 has been created and that the example code is connected to the MouseDown event of the RichTextBox.

В следующем примере демонстрируется использование различных событий мыши для рисования контура мыши на Panel . The following example demonstrates using different mouse events to draw the path of the mouse on a Panel. Сегмент линии добавляется в GraphicsPath для каждого MouseMove MouseDown события и, которое происходит. A line segment is added to the GraphicsPath for each MouseMove and MouseDown events that occur. Для обновления графики Invalidate вызывается метод для Panel каждого MouseDown MouseUp события и. To update the graphics, the Invalidate method is called for the Panel on each MouseDown and MouseUp event. Кроме того, при возникновении события графический контур прокручивается вверх или вниз MouseWheel . In addition, the graphic path is scrolled up or down when the MouseWheel event occurs. MouseHoverНа экране также идентифицируются дополнительные события мыши, например. Additional mouse events, like MouseHover, are identified on screen as well. Кроме того, на экране отображаются дополнительные сведения о мыши из SystemInformation класса. Also displayed on the screen is additional information about the mouse from the SystemInformation class.

Комментарии

Это перечисление используется многими классами, включая AxHost . Control DataGrid Form RadioButton Splitter StatusBar и UpDownBase . This enumeration is used by many classes, including AxHost, Control, DataGrid, Form, RadioButton, Splitter, StatusBar, and UpDownBase.

Mouse Buttons Enum

Definition

Specifies constants that define which mouse button was pressed.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

Fields

The left mouse button was pressed.

The middle mouse button was pressed.

No mouse button was pressed.

The right mouse button was pressed.

The first XButton (XBUTTON1) on Microsoft IntelliMouse Explorer was pressed.

The second XButton (XBUTTON2) on Microsoft IntelliMouse Explorer was pressed.

Examples

The following example demonstrates how to use the GetCharFromPosition method to obtain a character from the contents of a RichTextBox given its control coordinates. The example code uses coordinates located in the MouseEventArgs object passed as a parameter to the event handler to determine the location in the control to obtain the character. The character is then displayed in a MessageBox if it is not a space character. This example assumes that a RichTextBox control named richTextBox1 has been created and that the example code is connected to the MouseDown event of the RichTextBox.

The following example demonstrates using different mouse events to draw the path of the mouse on a Panel. A line segment is added to the GraphicsPath for each MouseMove and MouseDown events that occur. To update the graphics, the Invalidate method is called for the Panel on each MouseDown and MouseUp event. In addition, the graphic path is scrolled up or down when the MouseWheel event occurs. Additional mouse events, like MouseHover, are identified on screen as well. Also displayed on the screen is additional information about the mouse from the SystemInformation class.

How Mouse Input Works in Windows Forms

Receiving and handling mouse input is an important part of every Windows application. You can handle mouse events to perform an action in your application, or use mouse location information to perform hit testing or other actions. In addition, you can change the way the controls in your application handle mouse input. This topic describes these mouse events in detail, and how to obtain and change system settings for the mouse. For more information about the data provided with the mouse events and the order in which the mouse click events are raised, see Mouse Events in Windows Forms.

Mouse Location and Hit-Testing

When the user moves the mouse, the operating system moves the mouse pointer. The mouse pointer contains a single pixel, called the hot spot, which the operating system tracks and recognizes as the position of the pointer. When the user moves the mouse or presses a mouse button, the Control that contains the HotSpot raises the appropriate mouse event. You can obtain the current mouse position with the Location property of the MouseEventArgs when handling a mouse event or by using the Position property of the Cursor class. You can subsequently use mouse location information to perform hit-testing, and then perform an action based on the location of the mouse. Hit-testing capability is built in to several controls in Windows Forms such as the ListView, TreeView, MonthCalendar and DataGridView controls. Used with the appropriate mouse event, MouseHover for example, hit-testing is very useful for determining when your application should perform a specific action.

Mouse Events

The primary way to respond to mouse input is to handle mouse events. The following table shows the mouse events and describes when they are raised.

Mouse Event Description
Click This event occurs when the mouse button is released, typically before the MouseUp event. The handler for this event receives an argument of type EventArgs. Handle this event when you only need to determine when a click occurs.
MouseClick This event occurs when the user clicks the control with the mouse. The handler for this event receives an argument of type MouseEventArgs. Handle this event when you need to get information about the mouse when a click occurs.
DoubleClick This event occurs when the control is double-clicked. The handler for this event receives an argument of type EventArgs. Handle this event when you only need to determine when a double-click occurs.
MouseDoubleClick This event occurs when the user double-clicks the control with the mouse. The handler for this event receives an argument of type MouseEventArgs. Handle this event when you need to get information about the mouse when a double-click occurs.
MouseDown This event occurs when the mouse pointer is over the control and the user presses a mouse button. The handler for this event receives an argument of type MouseEventArgs.
MouseEnter This event occurs when the mouse pointer enters the border or client area of the control, depending on the type of control. The handler for this event receives an argument of type EventArgs.
MouseHover This event occurs when the mouse pointer stops and rests over the control. The handler for this event receives an argument of type EventArgs.
MouseLeave This event occurs when the mouse pointer leaves the border or client area of the control, depending on the type of the control. The handler for this event receives an argument of type EventArgs.
MouseMove This event occurs when the mouse pointer moves while it is over a control. The handler for this event receives an argument of type MouseEventArgs.
MouseUp This event occurs when the mouse pointer is over the control and the user releases a mouse button. The handler for this event receives an argument of type MouseEventArgs.
MouseWheel This event occurs when the user rotates the mouse wheel while the control has focus. The handler for this event receives an argument of type MouseEventArgs. You can use the Delta property of MouseEventArgs to determine how far the mouse has scrolled.

Changing Mouse Input and Detecting System Settings

You can detect and change the way a control handles mouse input by deriving from the control and using the GetStyle and SetStyle methods. The SetStyle method takes a bitwise combination of ControlStyles values to determine whether the control will have standard click or double-click behavior or if the control will handle its own mouse processing. In addition, the SystemInformation class includes properties that describe the capabilities of the mouse and specify how the mouse interacts with the operating system. The following table summarizes these properties.

Читайте также:  Удалить visual studio windows 10
Оцените статью