- Control. Mouse Click Event
- Definition
- Event Type
- Examples
- Remarks
- Как имитировать события мыши (Windows Forms .NET) How to simulate mouse events (Windows Forms .NET)
- События Events
- Вызов щелчка мышью Invoke a click
- PerformClick PerformClick
- InvokeClick InvokeClick
- Использование собственных методов Windows Use native Windows methods
- Событие MouseClick для программно созданных элементов
- Решение
- Осуществление ввода мышью в Windows Forms How Mouse Input Works in Windows Forms
- Расположение и Hit-Testing мыши Mouse Location and Hit-Testing
- События мыши Mouse Events
- Изменение ввода с помощью мыши и определение параметров системы Changing Mouse Input and Detecting System Settings
Control. Mouse Click Event
Definition
Occurs when the control is clicked by the mouse.
Event Type
Examples
The following code example demonstrates the use of this member. In the example, an event handler reports on the occurrence of the MouseClick event. This report helps you to learn when the event occurs and can assist you in debugging. To report on multiple events or on events that occur frequently, consider replacing MessageBox.Show with Console.WriteLine or appending the message to a multiline TextBox.
To run the example code, paste it into a project that contains an instance of a type that inherits from Control, such as a Button or ComboBox. Then name the instance Control1 and ensure that the event handler is associated with the MouseClick event.
Remarks
Depressing a mouse button when the cursor is over a control typically raises the following series of events from the control:
For this to occur, the various events cannot be disabled in the control’s class.
Two single clicks that occur close enough in time, as determined by the mouse settings of the user’s operating system, will generate a MouseDoubleClick event instead of the second MouseClick event.
Click events are logically higher-level events of a control. They are often raised by other actions, such as pressing the ENTER key when the control has focus.
For more information about handling events, see Handling and Raising Events.
Как имитировать события мыши (Windows Forms .NET) How to simulate mouse events (Windows Forms .NET)
Имитация событий мыши в Windows Forms не так проста, как имитация событий клавиатуры. Simulating mouse events in Windows Forms isn’t as straight forward as simulating keyboard events. В Windows Forms отсутствует вспомогательный класс для перемещения мыши и вызова действий щелчка мышью. Windows Forms doesn’t provide a helper class to move the mouse and invoke mouse-click actions. Единственным вариантом управления мышью является использование собственных методов Windows. The only option for controlling the mouse is to use native Windows methods. При работе с пользовательским элементом управления или формой можно имитировать событие мыши, но нельзя напрямую управлять мышью. If you’re working with a custom control or a form, you can simulate a mouse event, but you can’t directly control the mouse.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
События Events
У большинства событий есть соответствующий метод, который их вызывает, с шаблонным именем, начинающимся с On , за которым следует EventName , например OnMouseMove . Most events have a corresponding method that invokes them, named in the pattern of On followed by EventName , such as OnMouseMove . Этот вариант возможен только в пределах пользовательских элементов управления или форм, так как эти методы защищены и недоступны вне контекста элемента управления или формы. This option is only possible within custom controls or forms, because these methods are protected and can’t be accessed from outside the context of the control or form. Недостаток использования такого метода, как OnMouseMove , заключается в том, что он не управляет мышью или взаимодействует с элементом управления, а просто вызывает связанное событие. The disadvantage to using a method such as OnMouseMove is that it doesn’t actually control the mouse or interact with the control, it simply raises the associated event. Например, если вы хотите имитировать наведение указателя мыши на элемент в ListBox, OnMouseMove и ListBox не будут визуально реагировать на выделенный элемент под курсором. For example, if you wanted to simulate hovering over an item in a ListBox, OnMouseMove and the ListBox doesn’t visually react with a highlighted item under the cursor.
Эти защищенные методы можно использовать для имитации событий мыши. These protected methods are available to simulate mouse events.
- OnMouseDown
- OnMouseEnter
- OnMouseHover
- OnMouseLeave
- OnMouseMove
- OnMouseUp
- OnMouseWheel
- OnMouseClick
- OnMouseDoubleClick
Дополнительные сведения об этих событиях см. в разделе Использование событий мыши (Windows Forms .NET). For more information about these events, see Using mouse events (Windows Forms .NET)
Вызов щелчка мышью Invoke a click
Большинство элементов управления при щелчке мышью выполняют какое-либо действие, например вызов пользовательского кода при нажатии кнопки или изменение состояния флажка после его установки. Поэтому в Windows Forms предусмотрен простой способ запуска действия щелчка мышью. Considering most controls do something when clicked, like a button calling user code, or checkbox change its checked state, Windows Forms provides an easy way to trigger the click. Некоторые элементы управления, такие как ComboBox, не выполняют никаких специальных действий при щелчке мышью, а имитация щелчка не влияет на элемент управления. Some controls, such as a combobox, don’t do anything special when clicked and simulating a click has no effect on the control.
PerformClick PerformClick
Интерфейс System.Windows.Forms.IButtonControl предоставляет метод PerformClick, который имитирует щелчок элемента управления. The System.Windows.Forms.IButtonControl interface provides the PerformClick method which simulates a click on the control. Этот интерфейс реализуется как элементом управления System.Windows.Forms.Button, так и элементом управления System.Windows.Forms.LinkLabel. Both the System.Windows.Forms.Button and System.Windows.Forms.LinkLabel controls implement this interface.
InvokeClick InvokeClick
В форме с пользовательским элементом управления используйте метод InvokeOnClick для имитации щелчка мышью. With a form a custom control, use the InvokeOnClick method to simulate a mouse click. Это защищенный метод, который может вызываться только в форме или в производном пользовательском элементе управления. This is a protected method that can only be called from within the form or a derived custom control.
Например, ниже представлен код установки флажка в button1 . For example, the following code clicks a checkbox from button1 .
Использование собственных методов Windows Use native Windows methods
Windows предоставляет методы, которые можно вызывать для имитации движений мыши и щелчков мышью, такие как User32.dll SendInput и User32.dll SetCursorPos . Windows provides methods you can call to simulate mouse movements and clicks such as User32.dll SendInput and User32.dll SetCursorPos . В следующем примере курсор мыши перемещается в центр элемента управления: The following example moves the mouse cursor to the center of a control:
Событие MouseClick для программно созданных элементов
Событие для динамически созданных элементов
Добрый день. Мне необходимо вывести на форму несколько изображений (количество может меняться) и.
Массив программно созданных кнопок и событие к каждому из них
Предположим, у меня есть List . Для каждого string нужно создать Button. Каждому Button.
Получение данных с программно созданных элементов
Использую следующий код для программного создания DataGridView. Вопрос: Как теперь получить доступ.
Получение данных с программно созданных элементов
Программно создаю DataGridView И загружаю в него данные из базы данных. Вопрос: Как теперь.
Решение
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Событие MouseClick
Здравствуйте,господа.Подскажите мне, пожалуйста, как сделать клик по битмапу. Сам сделал, но.
Событие для динамически созданных ListBox
Дело в том что ListBox’ы были созданы а цикле таким образом: TListBox *btns = new.
Событие MouseClick в ListView
В приложении имеется ListView с 3 колонками. В 3 колонку записываются ссылки, по которым нужно.
Не обрабатывается событие MouseClick
Здравствуйте, помогите пожалуйста. Необходимо нарисовать круг по клику мыши, с центром в точке.
Событие OnClick для динамически созданных Image
Допустим есть массив из 3 Image созданный динамически как сделать ему событие onclick
Обработчик события для программно созданных кнопок
Помогите пожалуйста! Есть программно создаваемые кнопки в количестве, зависящем от введенного в.
Осуществление ввода мышью в Windows Forms How Mouse Input Works in Windows Forms
Получение и обработка ввода с помощью мыши является важной частью каждого приложения Windows. 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. Дополнительные сведения о данных, предоставляемых событиями мыши, и порядке, в котором вызываются события щелчка мыши, см. в разделе события мыши в Windows Forms. 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.
Расположение и Hit-Testing мыши 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. Когда пользователь перемещает мышь или нажимает кнопку мыши, объект Control , который содержит, HotSpot вызывает соответствующее событие мыши. When the user moves the mouse or presses a mouse button, the Control that contains the HotSpot raises the appropriate mouse event. Текущее расположение мыши можно получить с помощью Location свойства объекта MouseEventArgs при обработке события мыши или с помощью Position свойства Cursor класса. 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. Возможность проверки попадания встроена в несколько элементов управления в Windows Forms таких как ListView TreeView MonthCalendar DataGridView элементы управления, и. Hit-testing capability is built in to several controls in Windows Forms such as the ListView, TreeView, MonthCalendar and DataGridView controls. Например, при использовании соответствующего события мыши MouseHover для определения того, когда приложение должно выполнять определенное действие, полезно проверить попадание. 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 | Это событие возникает при отпускании кнопки мыши, как правило, перед MouseUp событием. This event occurs when the mouse button is released, typically before the MouseUp event. Обработчик этого события принимает аргумент типа EventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. 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. Обработчик этого события принимает аргумент типа EventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. 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. Обработчик этого события принимает аргумент типа EventArgs. 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. Обработчик этого события принимает аргумент типа EventArgs. 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. Обработчик этого события принимает аргумент типа EventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. 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. Обработчик этого события принимает аргумент типа MouseEventArgs. The handler for this event receives an argument of type MouseEventArgs. Свойство объекта можно использовать Delta MouseEventArgs для определения того, насколько прокручена мышь. You can use the Delta property of MouseEventArgs to determine how far the mouse has scrolled. |
Изменение ввода с помощью мыши и определение параметров системы Changing Mouse Input and Detecting System Settings
Можно обнаружить и изменить способ обработки ввода с помощью элемента управления, производного от элемента управления и используя GetStyle SetStyle методы и. You can detect and change the way a control handles mouse input by deriving from the control and using the GetStyle and SetStyle methods. SetStyleМетод принимает побитовое сочетание ControlStyles значений, чтобы определить, будет ли элемент управления иметь стандартное поведение щелчка или двойного щелчка, или если элемент управления будет обрабатывать свою собственную обработку мыши. 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. Кроме того, SystemInformation класс включает свойства, которые описывают возможности мыши и определяют взаимодействие мыши с операционной системой. 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.