Windows forms положение курсора

События мыши в формах Windows Forms Mouse Events in Windows Forms

При обработке ввода данных с помощью мыши обычно необходимо знать положение указателя и состояние кнопок мыши. When you handle mouse input, you usually want to know the location of the mouse pointer and the state of the mouse buttons. В этом разделе приводится подробная информация о получении этих сведений из событий мыши и описывается порядок, в котором вызываются события щелчка мыши в элементах управления Windows Forms. This topic provides details on how to get this information from mouse events, and explains the order in which mouse click events are raised in Windows Forms controls. Список и описание всех событий мыши см. в разделе как работает ввод с помощью мыши в Windows Forms. For a list and description of all of the mouse events, see How Mouse Input Works in Windows Forms. См. также обзор обработчиков событий (Windows Forms) и Общие сведения о событиях (Windows Forms). Also see Event Handlers Overview (Windows Forms) and Events Overview (Windows Forms).

Сведения о мыши Mouse Information

Объект MouseEventArgs отправляется обработчикам событий мыши, связанных с нажатием кнопки мыши и отслеживанием ее движений. A MouseEventArgs is sent to the handlers of mouse events related to clicking a mouse button and tracking mouse movements. Объект MouseEventArgs предоставляет сведения о текущем состоянии мыши, включая положение указателя мыши в клиентских координатах, какие кнопки мыши нажаты и произошла ли прокрутка колесика мыши. MouseEventArgs provides information about the current state of the mouse, including the location of the mouse pointer in client coordinates, which mouse buttons are pressed, and whether the mouse wheel has scrolled. Некоторые события мыши, например те, которые просто уведомляют о том, что указатель мыши пересек границы элемента управления, отправляют обработчику событий объект EventArgs без подробных сведений. Several mouse events, such as those that simply notify when the mouse pointer has entered or left the bounds of a control, send an EventArgs to the event handler with no further information.

Если нужно знать текущее состояние кнопок мыши или положение ее указателя, но при этом избежать обработки события мыши, можно также использовать свойства MouseButtons и MousePosition класса Control. If you want to know the current state of the mouse buttons or the location of the mouse pointer, and you want to avoid handling a mouse event, you can also use the MouseButtons and MousePosition properties of the Control class. Свойство MouseButtons возвращает сведения о том, какие кнопки мыши в настоящее время нажаты. MouseButtons returns information about which mouse buttons are currently pressed. Свойство MousePosition возвращает экранные координаты указателя мыши, которые эквивалентны значению, возвращаемому методом Position. The MousePosition returns the screen coordinates of the mouse pointer and is equivalent to the value returned by Position.

Преобразование между экранными и клиентскими координатами Converting Between Screen and Client Coordinates

Так как некоторые сведения о положении мыши представлены в клиентских координатах, а другие — в экранных, может потребоваться преобразовать точку из одной системы координат в другую. Because some mouse location information is in client coordinates and some is in screen coordinates, you may need to convert a point from one coordinate system to the other. Это легко сделать с помощью методов PointToClient и PointToScreen, доступных в классе Control. You can do this easily by using the PointToClient and PointToScreen methods available on the Control class.

Стандартное поведение события щелчка Standard Click Event Behavior

Если требуется обрабатывать события щелчка мыши в определенном порядке, необходимо знать порядок, в котором вызываются события щелчка в элементах управления Windows Forms. If you want to handle mouse click events in the proper order, you need to know the order in which click events are raised in Windows Forms controls. Когда кнопка мыши (любая) нажимается и отпускается, все элементы управления Windows Forms, кроме отмеченных в списке ниже, вызывают события щелчка в одном и том же порядке. All Windows Forms controls raise click events in the same order when a mouse button is pressed and released (regardless of which mouse button), except where noted in the following list for individual controls. Ниже приведен порядок событий, вызываемых одинарным щелчком мыши. The following list shows the order of events raised for a single mouse-button click:

Ниже приведен порядок событий, вызванных нажатием кнопки мыши двойным щелчком. The following is the order of events raised for a double mouse-button click:

Управление указателями мыши (Windows Forms .NET) Manage mouse pointers (Windows Forms .NET)

Указатель мыши, который иногда называют курсором, является точечным рисунком, указывающим на экране точку фокуса для ввода данных пользователем с помощью мыши. The mouse pointer, which is sometimes referred to as the cursor, is a bitmap that specifies a focus point on the screen for user input with the mouse. В этом разделе приводится обзор указателя мыши в Windows Forms и описываются некоторые способы его изменения и управления им. This topic provides an overview of the mouse pointer in Windows Forms and describes some of the ways to modify and control the mouse pointer.

Читайте также:  После обновления драйверов синий экран при загрузке windows

Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Доступ к указателю мыши Accessing the mouse pointer

Указатель мыши представлен классом Cursor, и каждый элемент Control имеет свойство Control.Cursor, которое задает для него указатель. The mouse pointer is represented by the Cursor class, and each Control has a Control.Cursor property that specifies the pointer for that control. Класс Cursor содержит свойства, описывающие указатель, например свойства Position и HotSpot, а также методы, которые могут изменять внешний вид указателя, например методы Show, Hide и DrawStretched. The Cursor class contains properties that describe the pointer, such as the Position and HotSpot properties, and methods that can modify the appearance of the pointer, such as the Show, Hide, and DrawStretched methods.

В следующем примере курсор скрывается при наведении курсора на кнопку: The following example hides the cursor when the cursor is over a button:

Управление указателем мыши Controlling the mouse pointer

Иногда может потребоваться ограничить область, в которой можно использовать указатель мыши, или изменить расположение мыши. Sometimes you may want to limit the area in which the mouse pointer can be used or change the position the mouse. Можно получить или задать текущее расположение мыши с помощью свойства Position объекта Cursor. You can get or set the current location of the mouse using the Position property of the Cursor. Кроме того, можно ограничить область, в которой можно использовать указатель мыши, задав свойство Clip. In addition, you can limit the area the mouse pointer can be used be setting the Clip property. По умолчанию областью действия является весь экран. The clip area, by default, is the entire screen.

В следующем примере указатель мыши помещается между двумя кнопками при их нажатии: The following example positions the mouse pointer between two buttons when they are clicked:

Изменение указателя мыши Changing the mouse pointer

Изменение указателя мыши является важным способом предоставления обратной связи пользователю. Changing the mouse pointer is an important way of providing feedback to the user. Например, указатель мыши можно изменить в обработчиках событий MouseEnter и MouseLeave, чтобы сообщить пользователю о том, что выполняются вычисления, и ограничить взаимодействие с пользователем в элементе управления. For example, the mouse pointer can be modified in the handlers of the MouseEnter and MouseLeave events to tell the user that computations are occurring and to limit user interaction in the control. Иногда указатель мыши изменяется из-за системных событий, например, когда приложение вовлечено в операцию перетаскивания. Sometimes, the mouse pointer will change because of system events, such as when your application is involved in a drag-and-drop operation.

Основной способ изменения указателя мыши заключается в присвоении свойству Control.Cursor или DefaultCursor элемента управления нового объекта Cursor. The primary way to change the mouse pointer is by setting the Control.Cursor or DefaultCursor property of a control to a new Cursor. Примеры изменения указателя мыши см. в примере кода в описании класса Cursor. For examples of changing the mouse pointer, see the code example in the Cursor class. Кроме того, класс Cursors предоставляет набор объектов Cursor для многих различных типов указателей, например указатель в виде руки. In addition, the Cursors class exposes a set of Cursor objects for many different types of pointers, such as a pointer that resembles a hand.

В следующем примере курсор мыши для кнопки меняется на руку: The following example changes the cursor of the mouse pointer for a button to a hand:

Чтобы отобразить указатель ожидания в виде песочных часов, когда указатель мыши находится на элементе управления, используйте свойство UseWaitCursor класса Control. To display the wait pointer, which resembles an hourglass, whenever the mouse pointer is on the control, use the UseWaitCursor property of the Control class.

Control. Mouse Position Свойство

Определение

Возвращает позицию указателя мыши в экранных координатах. Gets the position of the mouse cursor in screen coordinates.

Значение свойства

Объект Point содержит координаты указателя мыши относительно левого верхнего угла экрана. A Point that contains the coordinates of the mouse cursor relative to the upper-left corner of the screen.

Примеры

Следующий пример кода помещает TreeNode метку в изменяемое состояние, когда пользователь нажимает ALT + E, когда указатель мыши находится над узлом дерева. The following code example puts a TreeNode label into an editable state when the user presses ALT+E while the mouse cursor is over the tree node. После того как пользователь закончит редактирование метки, метки нельзя будет изменить, пока не будет нажата комбинация клавиш ALT + E. After the user is done editing the label, the labels cannot be edited again until the ALT+E key combination is pressed again. В этом примере требуется наличие TreeView в Form . This example requires that you have a TreeView on a Form. Представление в виде дерева также должно иметь по крайней мере одно значение TreeNode в Nodes коллекции. The tree view should also have at least one TreeNode in its Nodes collection.

Комментарии

MousePositionСвойство возвращает объект Point , представляющий позицию курсора мыши во время ссылки на свойство. The MousePosition property returns a Point that represents the mouse cursor position at the time the property was referenced. Координаты указывают позицию на экране, а не относительно элемента управления и возвращаются, независимо от того, наведен ли курсор на элемент управления. The coordinates indicate the position on the screen, not relative to the control, and are returned regardless of whether the cursor is positioned over the control. Координаты левого верхнего угла экрана равны 0, 0. The coordinates of the upper-left corner of the screen are 0,0.

Читайте также:  Драйвер для asus p7h55 windows 10

Получить координаты мышки относительно формы, но не экрана

Как получить координаты места клика мышью относительно объекта, а не формы
Как получить координаты места клика мышью относительно определенного объекта, а не формы.

Как получить координаты курсора относительно формы при нажатии кнопки мыши?
Всем привет! Как получить координаты курсора относительно формы при нажатии кнопки мыши? То есть.

Нужна программа, показывающая координаты мышки x,y экрана?
Нужна программа, показывающая координаты мышки x,y экрана в реальном времени? Можно исходные коды.

Решение

Смотри, раньше я делал так:

Но потом узнал про:

Тематические курсы и обучение профессиям онлайн
Профессия‌ С#-разработчик‌ (Skillbox)
Архитектор ПО (Skillbox)
Профессия Тестировщик (Skillbox)

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Вывести координаты курсора относительно экрана
Задача состоит в том, чтобы выводить координаты курсора относительно экрана. Возможно ли заменить.

Координаты ячейки Excel относительно экрана
Всем привет! Помогите. пожалуйста. Есть ли способ определить координаты ячейки Excel? Абсолютные.

Как получить координаты мышки и отслеживать их?
Хочу поработать с аналогом в Pygame: if event.type == pygame.MOUSEBUTTONDOWN , но чтобы событие.

Получить координаты мышки на форме, используя api функцию
Задание дали, получать координаты мышки на форме, используя api функцию в нэте нашёл 6.0 код.

Cursor Класс

Определение

Представляет изображение, используемое для рисования указателя мыши. Represents the image used to paint the mouse pointer.

Примеры

В следующем примере кода выводится форма, демонстрирующая использование пользовательского курсора. The following code example displays a form that demonstrates using a custom cursor. Пользователь Cursor внедряется в файл ресурсов приложения. The custom Cursor is embedded in the application’s resource file. В примере необходим курсор, содержащийся в файле курсора с именем MyCursor.cur . The example requires a cursor contained in a cursor file named MyCursor.cur . Чтобы скомпилировать этот пример с помощью командной строки, включите следующий флаг: /res:MyCursor.Cur, CustomCursor.MyCursor.Cur To compile this example using the command line, include the following flag: /res:MyCursor.Cur, CustomCursor.MyCursor.Cur

В следующем примере кода отображаются сведения о клиенте в TreeView элементе управления. The following code example displays customer information in a TreeView control. Узлы корневого дерева отображают имена клиентов, а дочерние узлы дерева отображают номера заказов, назначенные каждому клиенту. The root tree nodes display customer names, and the child tree nodes display the order numbers assigned to each customer. В этом примере 1 000 клиентов отображаются с 15 заказами. In this example, 1,000 customers are displayed with 15 orders each. Перерисовка TreeView отключается с помощью BeginUpdate EndUpdate методов и, а Cursor во время TreeView создания и прорисовки объектов отображается ожидание TreeNode . The repainting of the TreeView is suppressed by using the BeginUpdate and EndUpdate methods, and a wait Cursor is displayed while the TreeView creates and paints the TreeNode objects. В этом примере требуется, чтобы в каталоге приложения был указан файл курсора MyWait.cur . This example requires that you have a cursor file named MyWait.cur in the application directory. Также требуется Customer объект, который может содержать коллекцию Order объектов и был создан экземпляр TreeView элемента управления в Form . It also requires a Customer object that can hold a collection of Order objects, and that you have created an instance of a TreeView control on a Form.

Комментарии

Курсор представляет собой небольшое изображение, положение которого на экране управляется указывающим устройством, например мышью, пером или трекболом. A cursor is a small picture whose location on the screen is controlled by a pointing device, such as a mouse, pen, or trackball. Когда пользователь перемещает указывающее устройство, операционная система соответствующим образом перемещает курсор. When the user moves the pointing device, the operating system moves the cursor accordingly.

Для информирования пользователя о том, какая операция будет иметь мышь, используются разные фигуры курсора. Different cursor shapes are used to inform the user what operation the mouse will have. Например, при редактировании или выделении текста Cursors.IBeam обычно отображается курсор. For example, when editing or selecting text, a Cursors.IBeam cursor is typically displayed. Курсор ожидания обычно используется для информирования пользователя о том, что процесс выполняется в данный момент. A wait cursor is commonly used to inform the user that a process is currently running. Примеры процессов, которые может ожидать пользователь, — открытие файла, сохранение файла или заполнение элемента управления DataGrid , например, ListBox или TreeView с большим объемом данных. Examples of processes you might have the user wait for are opening a file, saving a file, or filling a control such as a DataGrid, ListBox or TreeView with a large amount of data.

Все элементы управления, производные от Control класса, имеют Cursor свойство. All controls that derive from the Control class have a Cursor property. Чтобы изменить курсор, отображаемый указателем мыши в пределах границ элемента управления, присвойте Cursor Cursor свойству элемента управления значение. To change the cursor displayed by the mouse pointer when it is within the bounds of the control, assign a Cursor to the Cursor property of the control. Кроме того, можно отобразить курсоры на уровне приложения, назначив Cursor Current свойству значение. Alternatively, you can display cursors at the application level by assigning a Cursor to the Current property. Например, если приложение предназначено для редактирования текстового файла, можно задать для свойства значение, чтобы Current Cursors.WaitCursor отображать курсор ожидания для приложения во время загрузки или сохранения файла, чтобы предотвратить обработку событий мыши. For example, if the purpose of your application is to edit a text file, you might set the Current property to Cursors.WaitCursor to display a wait cursor over the application while the file loads or saves to prevent any mouse events from being processed. По завершении процесса задайте для свойства значение, чтобы Current Cursors.Default приложение отображало соответствующий курсор для каждого типа элемента управления. When the process is complete, set the Current property to Cursors.Default for the application to display the appropriate cursor over each control type.

Читайте также:  Не работает экранная клавиатура windows 10 mobile

Если вы вызываете Application.DoEvents перед сбросом Current свойства обратно в Cursors.Default курсор, приложение возобновит прослушивание событий мыши и возобновит отображение соответствующего Cursor элемента управления в приложении. If you call Application.DoEvents before resetting the Current property back to the Cursors.Default cursor, the application will resume listening for mouse events and will resume displaying the appropriate Cursor for each control in the application.

Объекты Cursor можно создавать из нескольких источников, таких как маркер существующего Cursor , стандартного Cursor файла, ресурса или потока данных. Cursor objects can be created from several sources, such as the handle of an existing Cursor, a standard Cursor file, a resource, or a data stream.

CursorКласс не поддерживает анимированные курсоры (ANI-файлы) или курсоры с цветами, отличными от черного и белого. The Cursor class does not support animated cursors (.ani files) or cursors with colors other than black and white.

Если изображение, используемое в качестве курсора, слишком мало, можно использовать метод, DrawStretched чтобы заставить изображение заполнять границы курсора. If the image you are using as a cursor is too small, you can use the DrawStretched method to force the image to fill the bounds of the cursor. Можно временно скрыть курсор, вызвав Hide метод, и восстановить его, вызвав Show метод. You can temporarily hide the cursor by calling the Hide method, and restore it by calling the Show method.

Начиная с платформа .NET Framework 4.5.2, Cursor размер будет изменен на основе параметра dpi системы, если app.config файл содержит следующую запись: Starting with the .NET Framework 4.5.2, the Cursor will be resized based on the system DPI setting when the app.config file contains the following entry:

Конструкторы

Инициализирует новый экземпляр класса Cursor из указанного дескриптора Windows. Initializes a new instance of the Cursor class from the specified Windows handle.

Инициализирует новый экземпляр класса Cursor из указанного потока данных. Initializes a new instance of the Cursor class from the specified data stream.

Инициализирует новый экземпляр класса Cursor из указанного файла. Initializes a new instance of the Cursor class from the specified file.

Инициализирует новый экземпляр класса Cursor из указанного ресурса, используя указанный тип ресурса. Initializes a new instance of the Cursor class from the specified resource with the specified resource type.

Свойства

Возвращает или задает границы, представляющие прямоугольник отсечения для курсора. Gets or sets the bounds that represent the clipping rectangle for the cursor.

Возвращает или задает объект курсора, представляющий указатель мыши. Gets or sets a cursor object that represents the mouse cursor.

Возвращает дескриптор курсора. Gets the handle of the cursor.

Возвращает активную точку курсора. Gets the cursor hot spot.

Возвращает или задает положение курсора. Gets or sets the cursor’s position.

Возвращает размер объекта курсора. Gets the size of the cursor object.

Возвращает или задает объект, содержащий данные об элементе Cursor. Gets or sets the object that contains data about the Cursor.

Методы

Копирует дескриптор этого курсора Cursor. Copies the handle of this Cursor.

Освобождает все ресурсы, занятые модулем Cursor. Releases all resources used by the Cursor.

Рисует курсор на заданной поверхности в пределах указанных границ. Draws the cursor on the specified surface, within the specified bounds.

Рисует курсор в растянутом формате на указанной поверхности в пределах указанных границ. Draws the cursor in a stretched format on the specified surface, within the specified bounds.

Возвращает значение, показывающее, равен ли данный курсор указанному курсору Cursor. Returns a value indicating whether this cursor is equal to the specified Cursor.

Позволяет объекту попытаться освободить ресурсы и выполнить другие операции очистки, перед тем как он будет уничтожен во время сборки мусора. Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

Возвращает хэш-код для текущего объекта Cursor. Retrieves the hash code for the current Cursor.

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) Hide()

Скрывает курсор. Hides the cursor.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) Show()

Отображает курсор. Displays the cursor.

Возвращает удобную для восприятия строку, представляющую этот курсор Cursor. Retrieves a human readable string representing this Cursor.

Операторы

Возвращает значение, показывающее, являются ли эквивалентными экземпляры класса Cursor. Returns a value indicating whether two instances of the Cursor class are equal.

Возвращает значение, показывающее, являются ли два экземпляра класса Cursor неэквивалентными. Returns a value indicating whether two instances of the Cursor class are not equal.

Явные реализации интерфейса

Сериализирует объект. Serializes the object.

Оцените статью