Windows forms focus window

Содержание
  1. Control. Got Focus Событие
  2. Определение
  3. Тип события
  4. Примеры
  5. Комментарии
  6. Windows Form Window Always Focused?
  7. Control. Lost Focus Событие
  8. Определение
  9. Тип события
  10. Примеры
  11. Комментарии
  12. Порядок событий в формах Windows Forms Order of Events in Windows Forms
  13. События запуска и завершения работы приложения Application Startup and Shutdown Events
  14. События, связанные с фокусом и проверками Focus and Validation Events
  15. Windows Forms и архитектура ввода взаимодействия WPF Windows Forms and WPF Interoperability Input Architecture
  16. Немодальные формы и диалоговые окна Modeless Forms and Dialog Boxes
  17. WindowsFormsHost клавиатуры и обработки сообщений WindowsFormsHost Keyboard and Message Processing
  18. Получение сообщений из цикла обработки сообщений WPF Acquiring Messages from the WPF Message Loop
  19. Цикл обработки сообщений суррогатного Windows Forms Surrogate Windows Forms Message Loop
  20. Реализация IKeyboardInputSink IKeyboardInputSink Implementation
  21. Регистрация WindowsFormsHost WindowsFormsHost Registration
  22. Обработка клавиатуры и сообщений ElementHost ElementHost Keyboard and Message Processing
  23. Реализации интерфейса Interface Implementations
  24. Переходы и клавиши со стрелками Tabbing and Arrow Keys
  25. Ключи команд и диалоговые окна Command Keys and Dialog Box Keys
  26. Обработка ускорителя Accelerator Processing

Control. Got Focus Событие

Определение

Вызывается при получении фокуса элементом управления. Occurs when the control receives focus.

Тип события

Примеры

В следующем примере кода показано использование этого элемента. The following code example demonstrates the use of this member. В этом примере обработчик событий сообщает о возникновении GotFocus события. In the example, an event handler reports on the occurrence of the GotFocus event. Этот отчет поможет вам узнать, когда происходит событие и может помочь при отладке. This report helps you to learn when the event occurs and can assist you in debugging.

Чтобы выполнить пример кода, вставьте его в проект, содержащий экземпляр типа, наследуемого от Control , например Button или ComboBox . 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. Затем присвойте экземпляру имя Control1 и убедитесь, что обработчик событий связан с GotFocus событием. Then name the instance Control1 and ensure that the event handler is associated with the GotFocus event.

Комментарии

При изменении фокуса с помощью клавиатуры (TAB, SHIFT + TAB и т. д.), путем вызова Select SelectNextControl методов или или установки ContainerControl.ActiveControl свойства в текущую форму, события фокуса происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:

При изменении фокуса с помощью мыши или при вызове Focus метода события фокуса происходят в следующем порядке: When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Если CausesValidation свойство имеет значение false , Validating Validated события и подавляются. If the CausesValidation property is set to false , the Validating and Validated events are suppressed.

Примечание . GotFocus События и LostFocus — это события фокуса низкого уровня, привязанные к WM_KILLFOCUS и WM_SETFOCUS сообщениям Windows. Note The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Как правило, GotFocus LostFocus события и используются только при обновлении UICues или при записи пользовательских элементов управления. Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing custom controls. Вместо этого Enter Leave события и должны использоваться для всех элементов управления, кроме Form класса, который использует Activated события и Deactivate . Instead the Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events. Дополнительные сведения о GotFocus LostFocus событиях и см. в разделах WM_SETFOCUS и WM_KILLFOCUS . For more information about the GotFocus and LostFocus events, see the WM_SETFOCUS and WM_KILLFOCUS topics.

Не пытайтесь установить фокус с помощью Enter GotFocus Leave LostFocus Validating обработчиков событий. или Validated . Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Это может привести к тому, что ваше приложение или операционная система перестанут отвечать. Doing so can cause your application or the operating system to stop responding. Дополнительные сведения см. в разделе WM_KILLFOCUS . For more information, see the WM_KILLFOCUS topic.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Windows Form Window Always Focused?

I know there are a few threads about this already. What I need is to have a windows form window always focused meaning if I click on notepad or whatever program it will not enter any data in it and only enter data in my windows form textbox.

I found this code which works somewhat will explain more

this code seems to work well only when my project is opened meaning when my Visual Studio Project is closed the window is top most but doesn’t have focus meaning I can type inside other programs. Weird thing I found is that both notepad and my textbox had blinking line thing telling where you write the text. If I run my app from the Visual Studio project everything works as it should and when I try to click on other windows it won’t let me access which is what I want.

So I’m a bit confused on why it only works properly with the project opened

Also note as long as the project is opened then even .exe and other copys I made work properly I close the project solution and the program does what I explained above.

Just did some more testing and it seems to only work properly when this process is running vhost.exe which is the Visual Studio hosting process. I disabled it in the settings, and when I launch from VS it works fine but when I run just the exe in the bin folder I still get the weird results

EDIT

Here’s a quick video I made with my results http://www.youtube.com/watch?v=1ozpHSRGnMo

New Edit

What I did to fix this was set my app in a fullscreen mode kinda by doing this so the user can go clicking on other windows without closing this one first

Читайте также:  Обзор windows 10 для смартфона

Control. Lost Focus Событие

Определение

Происходит при потере фокуса элементом управления. Occurs when the control loses focus.

Тип события

Примеры

В следующем примере кода показано, как проверить текст для TextBox1. The following code example demonstrates validating the text for TextBox1. Он также демонстрирует обработку LostFocus события, присвоив FileDialog.InitialDirectory свойству текст в TextBox1. It also demonstrates handling the LostFocus event by setting the FileDialog.InitialDirectory property to the text in TextBox1. В примере кода используется ErrorProvider.GetError метод для проверки ошибки перед открытием диалогового окна файл. The code example used the ErrorProvider.GetError method to check for an error before opening the file dialog box. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую именованный, именованный, TextBox TextBox1 OpenFileDialog OpenFileDialog1 Button именованный Button1 и ErrorProvider именованный ErrorProvider1 . To run this example, paste the following code into a form containing a TextBox named TextBox1 , an OpenFileDialog named OpenFileDialog1 , a Button named Button1 , and an ErrorProvider named ErrorProvider1 . Убедитесь, что все события связаны с их обработчиками событий. Ensure all events are associated with their event handlers.

Комментарии

При изменении фокуса с помощью клавиатуры (TAB, SHIFT + TAB и т. д.), путем вызова Select SelectNextControl методов или или установки ContainerControl.ActiveControl свойства в текущую форму, события фокуса происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:

При изменении фокуса с помощью мыши или при вызове Focus метода события фокуса происходят в следующем порядке: When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Если CausesValidation свойство имеет значение false , Validating Validated события и подавляются. If the CausesValidation property is set to false , the Validating and Validated events are suppressed.

Если Cancel свойство объекта CancelEventArgs имеет значение true в Validating делегате события, все события, которые обычно возникают после Validating подавления события. If the Cancel property of the CancelEventArgs is set to true in the Validating event delegate, all events that would usually occur after the Validating event are suppressed.

GotFocusСобытия и LostFocus — это события фокуса низкого уровня, привязанные к WM_KILLFOCUS и WM_SETFOCUS сообщениям Windows. The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Как правило, GotFocus LostFocus события и используются только при обновлении UICues или при записи пользовательских элементов управления. Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing custom controls. Вместо этого Enter Leave события и должны использоваться для всех элементов управления, кроме Form класса, который использует Activated события и Deactivate . Instead the Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events. Дополнительные сведения о GotFocus LostFocus событиях и см. в разделах WM_KILLFOCUS и WM_KILLFOCUS . For more information about the GotFocus and LostFocus events, see the WM_KILLFOCUS and WM_KILLFOCUS topics.

Не пытайтесь установить фокус с помощью Enter GotFocus Leave LostFocus Validating обработчиков событий. или Validated . Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Это может привести к тому, что ваше приложение или операционная система перестанут отвечать. Doing so can cause your application or the operating system to stop responding. Дополнительные сведения см. в разделе WM_KILLFOCUS . For more information, see the WM_KILLFOCUS topic.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Порядок событий в формах Windows Forms Order of Events in Windows Forms

Особый интерес для разработчиков представляет порядок, в котором вызываются события в приложениях Windows Forms, для обеспечения обработки каждого из этих событий в свою очередь. The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. Если ситуация требует аккуратной обработки событий, например когда производится перерисовка части формы, то необходимо знать точный порядок, в котором вызываются события во время выполнения. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. В этом разделе приведены некоторые сведения о порядке событий, возникающих на нескольких важных этапах жизненного цикла приложений и элементов управления. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls. Конкретные сведения о порядке событий ввода мыши см. в разделе события мыши в Windows Forms. For specific details about the order of mouse input events, see Mouse Events in Windows Forms. Общие сведения о событиях в Windows Forms см. в разделе Общие сведения о событиях. For an overview of events in Windows Forms, see Events Overview. Дополнительные сведения о описывающего обработчиков событий см. в разделе Общие сведения об обработчиках событий. For details about the makeup of event handlers, see Event Handlers Overview.

События запуска и завершения работы приложения Application Startup and Shutdown Events

Классы Form и Control предоставляют набор событий, связанных с запуском и завершением приложения. The Form and Control classes expose a set of events related to application startup and shutdown. При запуске приложения Windows Forms события запуска главной формы вызываются в следующем порядке: When a Windows Forms application starts, the startup events of the main form are raised in the following order:

При закрытии приложения события запуска главной формы вызываются в следующем порядке: When an application closes, the shutdown events of the main form are raised in the following order:

Событие ApplicationExit класса Application вызывается после событий завершения работы основной формы. The ApplicationExit event of the Application class is raised after the shutdown events of the main form.

В Visual Basic 2005 содержатся дополнительные события приложений, такие как WindowsFormsApplicationBase.Startup и WindowsFormsApplicationBase.Shutdown. Visual Basic 2005 includes additional application events, such as WindowsFormsApplicationBase.Startup and WindowsFormsApplicationBase.Shutdown.

Читайте также:  Порты xbox live windows 10

События, связанные с фокусом и проверками Focus and Validation Events

При изменении фокуса с помощью клавиатуры (при нажатии клавиш TAB, SHIFT+TAB и так далее), путем вызова методов Select или SelectNextControl, либо присвоением свойства ActiveControl текущей форме, события фокуса ввода класса Control происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ActiveControl property to the current form, focus events of the Control class occur in the following order:

При изменении фокуса ввода с помощью мыши или путем вызова метода Focus события фокуса класса Control происходят в следующем порядке. When you change the focus by using the mouse or by calling the Focus method, focus events of the Control class occur in the following order:

Windows Forms и архитектура ввода взаимодействия WPF Windows Forms and WPF Interoperability Input Architecture

Для взаимодействия между WPF WPF и Windows Forms требуется, чтобы обе технологии имели соответствующую обработку ввода с клавиатуры. Interoperation between the WPF WPF and Windows Forms requires that both technologies have the appropriate keyboard input processing. В этом разделе описывается, как эти технологии реализуют обработку клавиатуры и сообщений для обеспечения беспрепятственного взаимодействия в гибридных приложениях. This topic describes how these technologies implement keyboard and message processing to enable smooth interoperation in hybrid applications.

В этом разделе содержатся следующие подразделы: This topic contains the following subsections:

Немодальные формы и диалоговые окна Modeless Forms and Dialog Boxes

WindowsFormsHost клавиатуры и обработки сообщений WindowsFormsHost Keyboard and Message Processing

Обработка клавиатуры и сообщений ElementHost ElementHost Keyboard and Message Processing

Немодальные формы и диалоговые окна Modeless Forms and Dialog Boxes

Вызовите EnableWindowsFormsInterop метод для WindowsFormsHost элемента, чтобы открыть немодальную форму или диалоговое окно из WPF WPF приложения на основе. Call the EnableWindowsFormsInterop method on the WindowsFormsHost element to open a modeless form or dialog box from a WPF WPF -based application.

Вызовите EnableModelessKeyboardInterop метод ElementHost элемента управления, чтобы открыть немодальную WPF WPF страницу в приложении на основе Windows Forms. Call the EnableModelessKeyboardInterop method on the ElementHost control to open a modeless WPF WPF page in a Windows Forms-based application.

WindowsFormsHost клавиатуры и обработки сообщений WindowsFormsHost Keyboard and Message Processing

При размещении WPF WPF приложения на основе Windows Forms обработка клавиатуры и сообщений состоит из следующих компонентов: When hosted by a WPF WPF -based application, Windows Forms keyboard and message processing consists of the following:

WindowsFormsHostКласс получает сообщения от WPF WPF цикла обработки сообщений, который реализуется ComponentDispatcher классом. The WindowsFormsHost class acquires messages from the WPF WPF message loop, which is implemented by the ComponentDispatcher class.

WindowsFormsHostКласс создает суррогатный Windows Forms цикле обработки сообщений, чтобы обеспечить нормальную Windows Formsную обработку клавиатуры. The WindowsFormsHost class creates a surrogate Windows Forms message loop to ensure that ordinary Windows Forms keyboard processing occurs.

WindowsFormsHostКласс реализует IKeyboardInputSink интерфейс для координации управления фокусом с WPF WPF . The WindowsFormsHost class implements the IKeyboardInputSink interface to coordinate focus management with WPF WPF .

WindowsFormsHostЭлементы управления регистрируются и запускают циклы сообщений. The WindowsFormsHost controls register themselves and start their message loops.

В следующих разделах эти части процесса описаны более подробно. The following sections describe these parts of the process in more detail.

Получение сообщений из цикла обработки сообщений WPF Acquiring Messages from the WPF Message Loop

ComponentDispatcherКласс реализует диспетчер циклов сообщений для WPF WPF . The ComponentDispatcher class implements the message loop manager for WPF WPF . ComponentDispatcherКласс предоставляет обработчики, позволяющие внешним клиентам фильтровать сообщения до WPF WPF их обработки. The ComponentDispatcher class provides hooks to enable external clients to filter messages before WPF WPF processes them.

Реализация взаимодействия обрабатывает ComponentDispatcher.ThreadFilterMessage событие, которое позволяет элементам управления Windows Forms обрабатывать сообщения перед WPF WPF элементами управления. The interoperation implementation handles the ComponentDispatcher.ThreadFilterMessage event, which enables Windows Forms controls to process messages before WPF WPF controls.

Цикл обработки сообщений суррогатного Windows Forms Surrogate Windows Forms Message Loop

По умолчанию System.Windows.Forms.Application класс содержит основной цикл обработки сообщений для Windows Forms приложений. By default, the System.Windows.Forms.Application class contains the primary message loop for Windows Forms applications. Во время взаимодействия цикл обработки сообщений Windows Forms не обрабатывает сообщения. During interoperation, the Windows Forms message loop does not process messages. Таким образом, эта логика должна быть воспроизведена. Therefore, this logic must be reproduced. Обработчик ComponentDispatcher.ThreadFilterMessage события выполняет следующие действия: The handler for the ComponentDispatcher.ThreadFilterMessage event performs the following steps:

Фильтрует сообщение с помощью IMessageFilter интерфейса. Filters the message using the IMessageFilter interface.

Переводит и отправляет сообщение, если оно требуется. Translates and dispatches the message, if it is required.

Передает сообщение в элемент управления размещения, если другие элементы управления не обрабатывают сообщение. Passes the message to the hosting control, if no other controls process the message.

Реализация IKeyboardInputSink IKeyboardInputSink Implementation

Суррогатный цикл обработки сообщений обрабатывает управление с помощью клавиатуры. The surrogate message loop handles keyboard management. Поэтому IKeyboardInputSink.TabInto метод является единственным IKeyboardInputSink элементом, для которого требуется реализация в WindowsFormsHost классе. Therefore, the IKeyboardInputSink.TabInto method is the only IKeyboardInputSink member that requires an implementation in the WindowsFormsHost class.

По умолчанию HwndHost класс возвращает false для своей IKeyboardInputSink.TabInto реализации. By default, the HwndHost class returns false for its IKeyboardInputSink.TabInto implementation. Это предотвращает переход от WPF WPF элемента управления к элементу управления Windows Forms. This prevents tabbing from a WPF WPF control to a Windows Forms control.

WindowsFormsHostРеализация IKeyboardInputSink.TabInto метода выполняет следующие действия: The WindowsFormsHost implementation of the IKeyboardInputSink.TabInto method performs the following steps:

Находит первый или последний элемент управления Windows Forms, который содержится в WindowsFormsHost элементе управления и может получать фокус. Finds the first or last Windows Forms control that is contained by the WindowsFormsHost control and that can receive focus. Выбор элемента управления зависит от сведений об обходах. The control choice depends on traversal information.

Устанавливает фокус на элемент управления и возвращает true . Sets focus to the control and returns true .

Если ни один из элементов управления не может получить фокус, возвращает false . If no control can receive focus, returns false .

Регистрация WindowsFormsHost WindowsFormsHost Registration

Когда создается обработчик окна для WindowsFormsHost элемента управления, WindowsFormsHost элемент управления вызывает внутренний статический метод, регистрирующий его присутствие в цикле обработки сообщений. When the window handle to a WindowsFormsHost control is created, the WindowsFormsHost control calls an internal static method that registers its presence for the message loop.

Читайте также:  Скрипт запуска файла linux

Во время регистрации WindowsFormsHost элемент управления проверяет цикл обработки сообщений. During registration, the WindowsFormsHost control examines the message loop. Если цикл обработки сообщений не запущен, ComponentDispatcher.ThreadFilterMessage создается обработчик событий. If the message loop has not been started, the ComponentDispatcher.ThreadFilterMessage event handler is created. Цикл обработки сообщений считается выполняющимся при ComponentDispatcher.ThreadFilterMessage присоединении обработчика событий. The message loop is considered to be running when the ComponentDispatcher.ThreadFilterMessage event handler is attached.

При уничтожении маркера окна WindowsFormsHost элемент управления удаляет себя из регистрации. When the window handle is destroyed, the WindowsFormsHost control removes itself from registration.

Обработка клавиатуры и сообщений ElementHost ElementHost Keyboard and Message Processing

При размещении в Windows Forms приложении WPF WPF обработка клавиатуры и сообщений состоит из следующих компонентов: When hosted by a Windows Forms application, WPF WPF keyboard and message processing consists of the following:

Переходы и клавиши со стрелками. Tabbing and arrow keys.

Ключи команд и диалоговые окна. Command keys and dialog box keys.

Windows Formsная обработка ускорителя. Windows Forms accelerator processing.

В следующих разделах эти компоненты описаны более подробно. The following sections describe these parts in more detail.

Реализации интерфейса Interface Implementations

В Windows Forms сообщения клавиатуры направляются в маркер окна элемента управления, который находится в фокусе. In Windows Forms, keyboard messages are routed to the window handle of the control that has focus. В ElementHost элементе управления эти сообщения направляются в размещенный элемент. In the ElementHost control, these messages are routed to the hosted element. Для этого ElementHost элемент управления предоставляет HwndSource экземпляр. To accomplish this, the ElementHost control provides an HwndSource instance. Если ElementHost элемент управления имеет фокус, то HwndSource экземпляр направляет большую часть ввода с клавиатуры, чтобы она могла быть обработана WPF WPF InputManager классом. If the ElementHost control has focus, the HwndSource instance routes most keyboard input so that it can be processed by the WPF WPF InputManager class.

Взаимодействие с клавиатурой зависит от реализации OnNoMoreTabStops метода для управления вводом клавиши TAB и клавиши со стрелкой, которая перемещает фокус из размещенных элементов. Keyboard interoperation relies on implementing the OnNoMoreTabStops method to handle TAB key and arrow key input that moves focus out of hosted elements.

Переходы и клавиши со стрелками Tabbing and Arrow Keys

Логика выбора Windows Forms сопоставляется с IKeyboardInputSink.TabInto OnNoMoreTabStops методами и для реализации навигации по клавишам Tab и клавиши со стрелкой. The Windows Forms selection logic is mapped to the IKeyboardInputSink.TabInto and OnNoMoreTabStops methods to implement TAB and arrow key navigation. При переопределении Select метода это сопоставление достигается. Overriding the Select method accomplishes this mapping.

Ключи команд и диалоговые окна Command Keys and Dialog Box Keys

Чтобы обеспечить WPF WPF первую возможность обработки ключей команд и диалоговых клавиш, Windows Forms Предварительная обработка команд подключается к TranslateAccelerator методу. To give WPF WPF the first opportunity to process command keys and dialog keys, Windows Forms command preprocessing is connected to the TranslateAccelerator method. Переопределение Control.ProcessCmdKey метода соединяет две технологии. Overriding the Control.ProcessCmdKey method connects the two technologies.

С помощью TranslateAccelerator метода размещенные элементы могут выполнять любые ключевые сообщения, такие как WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN или WM_SYSKEYUP, включая клавиши команд, такие как TAB, Enter, ESC и клавиши со стрелками. With the TranslateAccelerator method, the hosted elements can handle any key message, such as WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP, including command keys, such as TAB, ENTER, ESC, and arrow keys. Если сообщение ключа не обрабатывается, оно отправляется вверх по иерархии Windows Forms-предка для обработки. If a key message is not handled, it is sent up the Windows Forms ancestor hierarchy for handling.

Обработка ускорителя Accelerator Processing

Чтобы правильно обработать ускорители, Windows Formsная обработка ускорителя должна быть подключена к WPF WPF AccessKeyManager классу. To process accelerators correctly, Windows Forms accelerator processing must be connected to the WPF WPF AccessKeyManager class. Кроме того, все сообщения WM_CHAR должны быть правильно направлены в размещенные элементы. Additionally, all WM_CHAR messages must be correctly routed to hosted elements.

Поскольку HwndSource Реализация метода по умолчанию TranslateChar возвращает false , WM_CHAR сообщения обрабатываются с помощью следующей логики: Because the default HwndSource implementation of the TranslateChar method returns false , WM_CHAR messages are processed using the following logic:

Control.IsInputCharМетод переопределен, чтобы гарантировать, что все WM_CHAR сообщения пересылаются в размещенные элементы. The Control.IsInputChar method is overridden to ensure that all WM_CHAR messages are forwarded to hosted elements.

Если нажата клавиша ALT, сообщение будет WM_SYSCHAR. If the ALT key is pressed, the message is WM_SYSCHAR. Windows Forms не выполняет предварительную обработку этого сообщения с помощью IsInputChar метода. Windows Forms does not preprocess this message through the IsInputChar method. Таким образом, ProcessMnemonic метод переопределяется для запроса WPF WPF AccessKeyManager для зарегистрированного ускорителя. Therefore, the ProcessMnemonic method is overridden to query the WPF WPF AccessKeyManager for a registered accelerator. Если зарегистрированное сочетание клавиш найдено, AccessKeyManager обрабатывает его. If a registered accelerator is found, AccessKeyManager processes it.

Если клавиша ALT не нажата, WPF WPF InputManager класс обрабатывает необработанные входные данные. If the ALT key is not pressed, the WPF WPF InputManager class processes the unhandled input. Если входные данные являются ускорителем, то он AccessKeyManager обрабатывает его. If the input is an accelerator, the AccessKeyManager processes it. PostProcessInputСобытие обрабатывается для WM_CHAR сообщений, которые не были обработаны. The PostProcessInput event is handled for WM_CHAR messages that were not processed.

Когда пользователь нажимает клавишу ALT, визуальные подсказки ускорителя отображаются на всей форме. When the user presses the ALT key, accelerator visual cues are shown on the whole form. Для поддержки такого поведения все ElementHost элементы управления в активной форме получают WM_SYSKEYDOWN сообщения, независимо от того, какой элемент управления имеет фокус. To support this behavior, all ElementHost controls on the active form receive WM_SYSKEYDOWN messages, regardless of which control has focus.

Сообщения отправляются только ElementHost элементам управления в активной форме. Messages are sent only to ElementHost controls in the active form.

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