- Mouse Event Handler Делегат
- Определение
- Параметры
- Примеры
- Комментарии
- Методы расширения
- Mouse Event Args Class
- Definition
- Examples
- Remarks
- Constructors
- Properties
- Methods
- Mouse Event Args Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- Control. On Mouse Move(MouseEventArgs) Метод
- Определение
- Параметры
- Примеры
- Комментарии
- Примечания для тех, кто наследует этот метод
- Mouse Event Args Класс
- Определение
- Комментарии
- Конструкторы
- Свойства
- Методы
Mouse Event Handler Делегат
Определение
Представляет метод, который будет обрабатывать событие MouseDown , MouseUp или MouseMove формы, элемента управления или другого компонента. Represents the method that will handle the MouseDown , MouseUp , or MouseMove event of a form, control, or other component.
Параметры
Источник события. The source of the event.
Объект MouseEventArgs, содержащий данные события. A MouseEventArgs that contains the event data.
Примеры
В следующем примере кода показано использование различных событий мыши для рисования контура мыши на Panel . The following code 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.
Комментарии
При создании делегата MouseEventHandler необходимо указать метод, обрабатывающий событие. When you create a MouseEventHandler delegate, you identify the method that will handle the event. Чтобы связать событие с обработчиком событий, нужно добавить в событие экземпляр делегата. To associate the event with your event handler, add an instance of the delegate to the event. Обработчик событий вызывается всякий раз, когда происходит событие, если делегат не удален. The event handler is called whenever the event occurs, unless you remove the delegate. Дополнительные сведения об обработке событий с помощью делегатов см. в разделе обработка и вызов событий. For more information about handling events with delegates, see Handling and Raising Events.
Методы расширения
Получает объект, представляющий метод, представленный указанным делегатом. Gets an object that represents the method represented by the specified delegate.
Mouse Event Args Class
Definition
Provides data for the MouseUp, MouseDown, and MouseMove events.
Examples
The following code example handles the MouseDown event on a TextBox control so that clicking the right mouse button selects all the text in the control. This example requires that you have a form that contains a TextBox control that is named textBox1 .
The following code example uses the Location property to track clicks of the left mouse button and to draw a series of straight line segments in response to user input. The example does not redraw the lines if you hide the form and then redisplay it; this code has been omitted for simplicity.
The following code example uses the X and Y properties to display the current position of the mouse pointer in a ToolTip window.
Remarks
The MouseDown event occurs when the user presses the mouse button while the pointer is over a control. The MouseUp event occurs when the user releases the mouse button while the pointer remains over the control. The MouseMove event occurs when the user moves the mouse pointer over a control. A MouseEventArgs specifies which mouse button is pressed, how many times the mouse button was pressed and released, the coordinates of the mouse, and the amount the mouse wheel moved.
It is possible to receive a MouseDown event without a corresponding MouseUp, if the user switches focus to another application before releasing the mouse button.
These three events exist for the Control, AxHost, and NotifyIcon classes.
For information about the event model, see Handling and Raising Events.
Constructors
Initializes a new instance of the MouseEventArgs class.
Properties
Gets which mouse button was pressed.
Gets the number of times the mouse button was pressed and released.
Gets a signed count of the number of detents the mouse wheel has rotated, multiplied by the WHEEL_DELTA constant. A detent is one notch of the mouse wheel.
Gets the location of the mouse during the generating mouse event.
Gets the x-coordinate of the mouse during the generating mouse event.
Gets the y-coordinate of the mouse during the generating mouse event.
Methods
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Serves as the default hash function.
(Inherited from Object)
Gets the Type of the current instance.
(Inherited from Object)
Creates a shallow copy of the current Object.
(Inherited from Object)
Returns a string that represents the current object.
Mouse Event Args Класс
Определение
Предоставляет данные для событий MouseUp, MouseDown и MouseMove. Provides data for the MouseUp, MouseDown, and MouseMove events.
Примеры
В следующем примере кода событие обрабатывается MouseDown в TextBox элементе управления, чтобы при щелчке правой кнопкой мыши выбирался весь текст в элементе управления. The following code example handles the MouseDown event on a TextBox control so that clicking the right mouse button selects all the text in the control. В этом примере требуется форма, содержащая TextBox элемент управления с именем textBox1 . This example requires that you have a form that contains a TextBox control that is named textBox1 .
В следующем примере кода свойство используется Location для отслеживания щелчков левой кнопки мыши и для рисования ряда прямых линий в ответ на вводимые пользователем данные. The following code example uses the Location property to track clicks of the left mouse button and to draw a series of straight line segments in response to user input. В этом примере не выполняется перерисовка строк, если вы скрываете форму, а затем снова отображаете ее. Этот код был пропущен для простоты. The example does not redraw the lines if you hide the form and then redisplay it; this code has been omitted for simplicity.
В следующем примере кода X Свойства и используются Y для вывода текущей позиции указателя мыши в ToolTip окне. The following code example uses the X and Y properties to display the current position of the mouse pointer in a ToolTip window.
Комментарии
Это MouseDown событие возникает, когда пользователь нажимает кнопку мыши, когда указатель находится над элементом управления. The MouseDown event occurs when the user presses the mouse button while the pointer is over a control. Это MouseUp событие возникает, когда пользователь отпускает кнопку мыши, когда указатель остается над элементом управления. The MouseUp event occurs when the user releases the mouse button while the pointer remains over the control. Это MouseMove событие возникает, когда пользователь наводит указатель мыши на элемент управления. The MouseMove event occurs when the user moves the mouse pointer over a control. MouseEventArgsУказывает, какая кнопка мыши нажата, сколько раз была нажата кнопка мыши, координаты мыши и величину перемещения колесика мыши. A MouseEventArgs specifies which mouse button is pressed, how many times the mouse button was pressed and released, the coordinates of the mouse, and the amount the mouse wheel moved.
Событие может быть получено MouseDown без соответствующего события MouseUp , если пользователь переключает фокус на другое приложение, прежде чем отпустить кнопку мыши. It is possible to receive a MouseDown event without a corresponding MouseUp, if the user switches focus to another application before releasing the mouse button.
Эти три события существуют для Control классов, AxHost и NotifyIcon . These three events exist for the Control, AxHost, and NotifyIcon classes.
Дополнительные сведения о модели событий см. в разделе обработка и вызов событий. For information about the event model, see Handling and Raising Events.
Конструкторы
Инициализирует новый экземпляр класса MouseEventArgs. Initializes a new instance of the MouseEventArgs class.
Свойства
Возвращает значение, указывающее, какая кнопка мыши была нажата. Gets which mouse button was pressed.
Возвращает значение, указывающее, сколько раз была нажата и отпущена кнопка мыши. Gets the number of times the mouse button was pressed and released.
Получает значение со знаком, указывающее количество делений, на которое повернулось колесико мыши, умноженное на константу WHEEL_DELTA. Gets a signed count of the number of detents the mouse wheel has rotated, multiplied by the WHEEL_DELTA constant. Делением называется один зубец колесика мыши. A detent is one notch of the mouse wheel.
Возвращает расположение указателя мыши в момент создания события мыши. Gets the location of the mouse during the generating mouse event.
Возвращает координату X указателя мыши в момент создания события мыши. Gets the x-coordinate of the mouse during the generating mouse event.
Возвращает координату Y указателя мыши в момент создания события мыши. Gets the y-coordinate of the mouse during the generating mouse event.
Методы
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
Control. On Mouse Move(MouseEventArgs) Метод
Определение
Вызывает событие MouseMove. Raises the MouseMove event.
Параметры
Объект MouseEventArgs, содержащий данные события. A MouseEventArgs that contains the event data.
Примеры
В следующем примере кода показано, как переопределить OnMouseHover методы и OnMouseMove в производном классе. The following code example demonstrates how to override the OnMouseHover and OnMouseMove methods in a derived class. Чтобы выполнить пример, вставьте следующий код в новую форму и вставьте этот класс, формируя тот же файл после формы. To run the example, paste the following code in a new form and paste this class, forming the same file, after the form. Добавьте в форму кнопку типа FunButton . Add a button of type FunButton to the form.
Комментарии
При возникновении события через делегат вызывается обработчик события. Raising an event invokes the event handler through a delegate. Дополнительные сведения см. в разделе обработка и вызов событий. For more information, see Handling and Raising Events.
Метод OnMouseMove также позволяет производным классам обрабатывать событие, не присоединяя делегат. The OnMouseMove method also allows derived classes to handle the event without attaching a delegate. Это предпочтительная методика обработки событий в производном классе. This is the preferred technique for handling the event in a derived class.
Примечания для тех, кто наследует этот метод
При переопределении метода OnMouseMove(MouseEventArgs) в производном классе нужно убедиться, что вызывается метод OnMouseMove(MouseEventArgs) базового класса, чтобы зарегистрированные делегаты получили событие. When overriding OnMouseMove(MouseEventArgs) in a derived class, be sure to call the base class’s OnMouseMove(MouseEventArgs) method so that registered delegates receive the event.
Mouse Event Args Класс
Определение
Предоставляет данные для связанных с мышью маршрутизируемых событий, не включающих события, связанные с кнопками мыши или колесиком мыши, например MouseMove. Provides data for mouse related routed events that do not specifically involve mouse buttons or the mouse wheel, for example MouseMove.
Комментарии
Этот класс данных события используется со следующими вложенными событиями. This event data class is used with the following attached events.
Этот класс данных события используется со следующими перенаправленными событиями. This event data class is used with the following routed events. Эти перенаправленные события перенаправляют ранее упомянутые вложенные события, чтобы сделать их более доступными для модели общего элемента в WPF. These routed events forward the previously listed attached events to make them more accessible to the general element model in WPF.
Вложенные события и перенаправляемые события базового элемента совместно используют свои данные событий, а версии с восходящей маршрутизацией и туннелирования перенаправленных событий также используют совместное использование данных о событиях. The attached events and the base element routed events share their event data, and the bubbling and tunneling versions of the routed events also share event data. Это может повлиять на обрабатываемые характеристики события, когда оно перемещается в маршрут события. This can affect the handled characteristics of the event as it travels the event route. Дополнительные сведения см. в разделе Общие сведения о входных данных. For details, see Input Overview.
В отличие от RoutedEventArgs свойств, относящихся к перенаправленным событиям, наиболее интересные свойства MouseEventArgs , которые можно использовать в MouseEventHandler реализации, — это несколько свойств, которые предоставляют текущее состояние кнопки (например, LeftButton ) и MouseDevice ). Other than the RoutedEventArgs properties that are relevant for all routed events, the most interesting properties of MouseEventArgs that you might use in a MouseEventHandler implementation are several properties that expose the current button state (such as LeftButton) and MouseDevice). MouseDevice полезен в частности, так как вы можете проверить Captured его. MouseDevice is useful particularly because you can check Captured on it.
Обратите внимание, что события, относящиеся к событиям кнопки мыши, используют другой класс данных событий MouseButtonEventArgs . Note that events that specifically deal with mouse button events use a different event data class, MouseButtonEventArgs. Свойства кнопки мыши доступны MouseEventArgs в, если имеются режимы ввода или взаимодействия, использующие кнопки, даже если обрабатывается событие, не являющееся кнопкой. The mouse button properties are available on MouseEventArgs in case there are input modes or interactions that involve the buttons even if you are handling a non-button event.
MouseКласс предоставляет дополнительные свойства и методы для определения состояния мыши. The Mouse class provides additional properties and methods for determining the state of the mouse.
Конструкторы
Инициализирует новый экземпляр класса MouseEventArgs, используя указанный объект MouseDevice и метку времени. Initializes a new instance of the MouseEventArgs class using the specified MouseDevice and timestamp.
Инициализирует новый экземпляр класса MouseEventArgs, используя указанный объект MouseDevice, отметку времени и StylusDevice. Initializes a new instance of the MouseEventArgs class using the specified MouseDevice, timestamp, and StylusDevice.
Свойства
Получает устройство ввода, инициировавшее это событие. Gets the input device that initiated this event.
(Унаследовано от InputEventArgs)
Получает или задает значение, обозначающее текущее состояние обработки перенаправленного события при перемещении по маршруту. Gets or sets a value that indicates the present state of the event handling for a routed event as it travels the route.
(Унаследовано от RoutedEventArgs)
Получает текущее состояние левой кнопки мыши. Gets the current state of the left mouse button.
Получает текущее состояние средней кнопки мыши. Gets the current state of the middle mouse button.
Получает устройство мыши, связанное с этим событием. Gets the mouse device associated with this event.
Возвращает исходный источник отчетов, определяемый чистой проверкой нажатия до какой-либо возможной корректировки Source родительским классом. Gets the original reporting source as determined by pure hit testing, before any possible Source adjustment by a parent class.
(Унаследовано от RoutedEventArgs)
Получает текущее состояние правой кнопки мыши. Gets the current state of the right mouse button.
Возвращает или задает объект RoutedEvent, связанный с этим экземпляром RoutedEventArgs. Gets or sets the RoutedEvent associated with this RoutedEventArgs instance.
(Унаследовано от RoutedEventArgs)
Получает или задает ссылку на объект, создавший событие. Gets or sets a reference to the object that raised the event.
(Унаследовано от RoutedEventArgs)
Получает устройство пера, связанное с этим событием. Gets the stylus device associated with this event.
Получает время, когда произошло данное событие. Gets the time when this event occurred.
(Унаследовано от InputEventArgs)
Получает текущее состояние первой расширенной кнопки мыши. Gets the current state of the first extended mouse button.
Получает текущее состояние второй расширенной кнопки мыши. Gets the state of the second extended mouse button.
Методы
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает позицию указателя мыши относительно заданного элемента. Returns the position of the mouse pointer relative to the specified element.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Вызывает обработчики событий способом, зависящим от типа, что может повысить эффективность системы событий. Invokes event handlers in a type-specific way, which can increase event system efficiency.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
При переопределении в производном классе предоставляет точку входа обратного вызова для уведомления в случае изменения значения свойства Source в экземпляре. When overridden in a derived class, provides a notification callback entry point whenever the value of the Source property of an instance changes.
(Унаследовано от RoutedEventArgs)
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.