Windows forms cursor position

Cursor. Position Свойство

Определение

Получает или задает положение курсора. Gets or sets the position of a cursor.

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

Позиция курсора. The position of a cursor.

Комментарии

Это свойство можно использовать для получения позиции курсора, а также для программного задания положения курсора. This property can be used to get the position of a cursor, as well as to programmatically set the cursor position.

Место измеряется как значение оси, к которой принадлежит курсор, что определяется AxisType свойством. The position is measured as a value of the axis that the cursor belongs to, which is determined by the AxisType property. Например, если курсор принадлежит к первичной оси X, то при установке этого свойства в значение 1 января 2000 будет отображаться курсор на оси X в положении 1 января 2000 вдоль оси. For example, if the cursor belongs to the primary X axis, then setting this property to a value of January 1, 2000 will result in the X-axis cursor being drawn at the January 1, 2000 position along the axis. Если это значение оси не существует, курсор не будет отображаться. If this axis value does not exist, the cursor will not be displayed.

Обратите внимание, что если задать это свойство, свойства и не будут иметь никакого значения, то Interval IntervalOffset есть курсор будет отображаться в указанном месте. Note that if you set this property, the Interval and IntervalOffset properties will have no effect; that is, the cursor will be displayed at this specified location.

Задание этого свойства не приведет к вызову CursorPositionChanged CursorPositionChanging событий или. Setting this property will not raise the CursorPositionChanged or CursorPositionChanging events.

Кроме того, SetCursorPosition SetCursorPixelPosition для установки курсора можно использовать методы и. Alternatively, the SetCursorPosition and SetCursorPixelPosition methods can be used to set the cursor.

Чтобы программно удалить курсор, используйте это свойство, чтобы установить позицию курсора в NaN . To programmatically remove a cursor, use this property to set the position of the cursor to NaN.

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.

Читайте также:  Сервер rust для windows

Комментарии

Курсор представляет собой небольшое изображение, положение которого на экране управляется указывающим устройством, например мышью, пером или трекболом. 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.

Если вы вызываете 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.

Читайте также:  Во время установки windows компьютер зависает

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.

Читайте также:  Как создать запароленную папку windows 10

Создает неполную копию текущего объекта 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.

Console. Set Cursor Position(Int32, Int32) Метод

Определение

Устанавливает положение курсора. Sets the position of the cursor.

Параметры

Позиция столбца курсора. The column position of the cursor. Столбцы нумеруются как слева направо, начинается с 0. Columns are numbered from left to right starting at 0.

Позиция строки курсора. The row position of the cursor. Строки пронумерованы сверху вниз, начиная с 0. Rows are numbered from top to bottom starting at 0.

Исключения

Значение параметра left или top меньше нуля. left or top is less than zero.

Значение параметра left больше или равно значению свойства BufferWidth. left is greater than or equal to BufferWidth.

Значение top больше или равно BufferHeight. top is greater than or equal to BufferHeight.

Пользователь не имеет разрешений на выполнение этого действия. The user does not have permission to perform this action.

Ошибка ввода/вывода. An I/O error occurred.

Примеры

В этом примере демонстрируются CursorLeft CursorTop Свойства и, а SetCursorPosition также Clear методы и. This example demonstrates the CursorLeft and CursorTop properties, and the SetCursorPosition and Clear methods. В примере размещается курсор, который определяет, где будет выполняться следующая запись, чтобы нарисовать 5-символьный прямоугольник на 5 символов, используя сочетание строк «+», «|» и «-«. The example positions the cursor, which determines where the next write will occur, to draw a 5 character by 5 character rectangle using a combination of «+», «|», and «-» strings. Обратите внимание, что прямоугольник может быть нарисован с меньшим количеством шагов, используя сочетание других строк. Note that the rectangle could be drawn with fewer steps using a combination of other strings.

Комментарии

Используйте SetCursorPosition метод, чтобы указать, где должна начинаться следующая операция записи в окне консоли. Use the SetCursorPosition method to specify where the next write operation in the console window is to begin. Если указанная положение курсора находится за пределами области, видимой в окне консоли, то источник окна автоматически изменяется, чтобы сделать курсор видимым. If the specified cursor position is outside the area that is currently visible in the console window, the window origin changes automatically to make the cursor visible.

Курсор автоматически перемещается к следующему положению символа каждый раз, когда символ записывается в окно консоли. The cursor automatically moves to the next character position each time a character is written to the console window. Если курсор находится в нижнем правом положении окна консоли, следующая операция записи приводит к прокрутке окна консоли таким образом, чтобы курсор оставался видимым. If the cursor is at the bottom right character position of the console window, the next write operation causes the console window to scroll so the cursor remains visible. Если вы хотите записать символ в нижнюю правую точку, не вызывая прокрутки окна консоли, используйте MoveBufferArea метод для перемещения символа в эту точку. If you want to write a character to the bottom right character position without causing the console window to scroll, use the MoveBufferArea method to move a character to that position.

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