- Как получить окне консоли (HWND)
- Аннотация
- Дополнительные сведения
- Пример кода
- ShowWindow function (winuser.h)
- Syntax
- Parameters
- Return value
- Remarks
- Using Window Procedures
- Designing a Window Procedure
- Associating a Window Procedure with a Window Class
- Subclassing a Window
- GetWindow function (winuser.h)
- Syntax
- Parameters
- Return value
- Remarks
- Hwnd Source Класс
- Определение
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
- Явные реализации интерфейса
Как получить окне консоли (HWND)
В этой статье описывается, как получить окне консоли (HWND).
Исходная версия продукта: Windows Server 2012 R2
Исходный номер КБ: 124103
Аннотация
Может быть полезно управлять окном, связанным с консольным приложением. API Win32 не предоставляет прямого метода получения окне, связанного с консольным приложением. Однако вы можете получить окне, вызывая FindWindow() . Эта функция извлекает окне на основе имени класса или имени окна.
Вызов GetConsoleTitle() для определения текущего заголовка консоли. Затем укавит текущее название FindWindow() консоли.
Дополнительные сведения
Так как несколько окон могут иметь одно и то же название, необходимо изменить заголовок текущего окна консоли на уникальный заголовок. Это поможет предотвратить возврат неправильного окне. Используется SetConsoleTitle() для изменения текущего заголовка окна консоли. Вот как это происходит:
Вызов GetConsoleTitle() для сохранения заголовка текущего окна консоли.
Вызов, SetConsoleTitle() чтобы изменить заголовок консоли на уникальный заголовок.
Вызовите спящий режим (40), чтобы убедиться, что заголовок окна обновлен.
Вызов FindWindow (NULL, uniquetitle), чтобы получить HWND, этот вызов возвращает HWND или NULL, если операция не удалась.
Вызовите SetConsoleTitle() вызов со значением, полученным на шаге 1, для восстановления исходного заголовка окна.
Следует протестировать итоговый HWND. Например, можно проверить, соответствует ли возвращенный HWND текущему процессу, вызывая HWND и сравнивая результат GetWindowText() с GetConsoleTitle() .
Итоговая HWND не гарантируется для всех операций обработки окон.
Пример кода
Следующая функция извлекает текущий окне окна консольного приложения (HWND). В случае успешного функционирования функции возвращаемое значение является окну консоли. Если функция не работает, возвращается значение NULL. Для краткости некоторые проверки ошибок опущены.
ShowWindow function (winuser.h)
Sets the specified window’s show state.
Syntax
Parameters
A handle to the window.
Controls how the window is to be shown. This parameter is ignored the first time an application calls ShowWindow, if the program that launched the application provides a STARTUPINFO structure. Otherwise, the first time ShowWindow is called, the value should be the value obtained by the WinMain function in its nCmdShow parameter. In subsequent calls, this parameter can be one of the following values.
Value | Meaning |
---|---|
SW_FORCEMINIMIZE 11 | Minimizes a window, even if the thread that owns the window is not responding. This flag should only be used when minimizing windows from a different thread. |
SW_HIDE 0 | Hides the window and activates another window. |
SW_MAXIMIZE 3 | Maximizes the specified window. |
SW_MINIMIZE 6 | Minimizes the specified window and activates the next top-level window in the Z order. |
SW_RESTORE 9 | Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window. |
SW_SHOW 5 | Activates the window and displays it in its current size and position. |
SW_SHOWDEFAULT 10 | Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. |
SW_SHOWMAXIMIZED 3 | Activates the window and displays it as a maximized window. |
SW_SHOWMINIMIZED 2 | Activates the window and displays it as a minimized window. |
SW_SHOWMINNOACTIVE 7 | Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated. |
SW_SHOWNA 8 | Displays the window in its current size and position. This value is similar to SW_SHOW, except that the window is not activated. |
SW_SHOWNOACTIVATE 4 | Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except that the window is not activated. |
SW_SHOWNORMAL 1 | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. |
Return value
If the window was previously visible, the return value is nonzero.
If the window was previously hidden, the return value is zero.
Remarks
To perform certain special effects when showing or hiding a window, use AnimateWindow.
The first time an application calls ShowWindow, it should use the WinMain function’s nCmdShow parameter as its nCmdShow parameter. Subsequent calls to ShowWindow must use one of the values in the given list, instead of the one specified by the WinMain function’s nCmdShow parameter.
As noted in the discussion of the nCmdShow parameter, the nCmdShow value is ignored in the first call to ShowWindow if the program that launched the application specifies startup information in the structure. In this case, ShowWindow uses the information specified in the STARTUPINFO structure to show the window. On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT to use the startup information provided by the program that launched the application. This behavior is designed for the following situations:
- Applications create their main window by calling CreateWindow with the WS_VISIBLE flag set.
- Applications create their main window by calling CreateWindow with the WS_VISIBLE flag cleared, and later call ShowWindow with the SW_SHOW flag set to make it visible.
Using Window Procedures
This section explains how to perform the following tasks associated with window procedures.
Designing a Window Procedure
The following example shows the structure of a typical window procedure. The window procedure uses the message argument in a switch statement with individual messages handled by separate case statements. Notice that each case returns a specific value for each message. For messages that it does not process, the window procedure calls the DefWindowProc function.
The WM_NCCREATE message is sent just after your window is created, but if an application responds to this message by returning FALSE, CreateWindowEx function fails. The WM_CREATE message is sent after your window is already created.
The WM_DESTROY message is sent when your window is about to be destroyed. The DestroyWindow function takes care of destroying any child windows of the window being destroyed. The WM_NCDESTROY message is sent just before a window is destroyed.
At the very least, a window procedure should process the WM_PAINT message to draw itself. Typically, it should handle mouse and keyboard messages as well. Consult the descriptions of individual messages to determine whether your window procedure should handle them.
Your application can call the DefWindowProc function as part of the processing of a message. In such a case, the application can modify the message parameters before passing the message to DefWindowProc, or it can continue with the default processing after performing its own operations.
A dialog box procedure receives a WM_INITDIALOG message instead of a WM_CREATE message and does not pass unprocessed messages to the DefDlgProc function. Otherwise, a dialog box procedure is exactly the same as a window procedure.
Associating a Window Procedure with a Window Class
You associate a window procedure with a window class when registering the class. You must fill a WNDCLASS structure with information about the class, and the lpfnWndProc member must specify the address of the window procedure. To register the class, pass the address of WNDCLASS structure to the RegisterClass function. After the window class has been registered, the window procedure is automatically associated with each new window created with that class.
The following example shows how to associate the window procedure in the previous example with a window class.
Subclassing a Window
To subclass an instance of a window, call the SetWindowLong function and specify the handle to the window to subclass the GWL_WNDPROC flag and a pointer to the subclass procedure. SetWindowLong returns a pointer to the original window procedure; use this pointer to pass messages to the original procedure. The subclass window procedure must use the CallWindowProc function to call the original window procedure.
To write code that is compatible with both 32-bit and 64-bit versions of Windows, use the SetWindowLongPtr function.
The following example shows how to subclass an instance of an edit control in a dialog box. The subclass window procedure enables the edit control to receive all keyboard input, including the ENTER and TAB keys, whenever the control has the input focus.
GetWindow function (winuser.h)
Retrieves a handle to a window that has the specified relationship (Z-Order or owner) to the specified window.
Syntax
Parameters
A handle to a window. The window handle retrieved is relative to this window, based on the value of the uCmd parameter.
The relationship between the specified window and the window whose handle is to be retrieved. This parameter can be one of the following values.
Value | Meaning |
---|---|
GW_CHILD 5 | The retrieved handle identifies the child window at the top of the Z order, if the specified window is a parent window; otherwise, the retrieved handle is NULL. The function examines only child windows of the specified window. It does not examine descendant windows. |
GW_ENABLEDPOPUP 6 | The retrieved handle identifies the enabled popup window owned by the specified window (the search uses the first such window found using GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the retrieved handle is that of the specified window. |
GW_HWNDFIRST 0 | The retrieved handle identifies the window of the same type that is highest in the Z order. If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window. |
GW_HWNDLAST 1 | The retrieved handle identifies the window of the same type that is lowest in the Z order. If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window. |
GW_HWNDNEXT 2 | The retrieved handle identifies the window below the specified window in the Z order. If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window. |
GW_HWNDPREV 3 | The retrieved handle identifies the window above the specified window in the Z order. If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window. |
GW_OWNER 4 | The retrieved handle identifies the specified window’s owner window, if any. For more information, see Owned Windows. |
Return value
If the function succeeds, the return value is a window handle. If no window exists with the specified relationship to the specified window, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The EnumChildWindows function is more reliable than calling GetWindow in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.
Hwnd Source Класс
Определение
Представляет содержимое Windows Presentation Foundation (WPF) в окне Win32. Presents Windows Presentation Foundation (WPF) content in a Win32 window.
Комментарии
Многие члены этого класса недоступны в зоне безопасности Интернета. Many members of this class are unavailable in the Internet security zone.
Класс HwndSource реализует окно Win32, которое может содержать содержимое WPF. An HwndSource implements a Win32 window that can contain WPF content. Содержимое WPF в окне упорядочивается, измеряется и готовится к просмотру. и является интерактивным для входных данных. The WPF content in the window is arranged, measured, and rendered; and is interactive to input. Поскольку HwndSource компонент специально разработан для взаимодействия с Win32, этот класс предоставляет несколько низкоуровневых функций Win32. Because the HwndSource is specifically designed to interoperate with Win32, this class exposes several low-level Win32 features. Этот класс можно использовать для следующих задач: You can use this class to do the following:
Укажите стили окон, стили классов окон и расширенные стили окна. Specify window styles, window class styles, and extended window styles.
Подсоедините процедуру окна. Hook the window procedure.
Предоставление доступа к дескриптору окна (HWND). Provide access to the window handle (HWND).
Уничтожить окно. Destroy the window.
HwndSourceКласс предназначен для общего взаимодействия и не предназначен для управляемой оболочки HWND. The HwndSource class is designed for general interoperability and is not designed as a managed HWND wrapper. Как правило, он не предоставляет управляемые методы для управления окном или свойствами для проверки его состояния. In general, it does not provide managed methods for manipulating the window or properties for inspecting its state. Вместо этого HwndSource класс предоставляет доступ к дескриптору окна Win32 (HWND) через Handle свойство, которое можно передать с помощью методов PInvoke API-интерфейсам Win32 для управления окном. Instead, the HwndSource class provides access to the Win32 window handle (HWND) through the Handle property, which can be passed by means of PInvoke techniques to Win32 APIs in order to manipulate the window.
Строительство Construction
Многие аспекты HwndSource можно указывать только во время создания. Many aspects of the HwndSource can only be specified at construction time. Чтобы создать HwndSource , сначала создайте HwndSourceParameters структуру и заполните ее нужными параметрами. To create an HwndSource, first create an HwndSourceParameters structure and populate it with the desired parameters. К этим параметрам относятся следующие. These parameters include the following:
Классы, окна и расширенные стили окна. The class, window, and extended window styles. Для изменения стилей после создания окна необходимо использовать PInvoke. You must use PInvoke to change the styles after the window is created. Не все стили можно изменить после создания окна. Not all styles can be changed after the window is created. Перед изменением стилей окна обратитесь к документации по Win32. Consult the Win32 documentation before changing window styles.
Начальное расположение окна. The initial position of the window.
Начальный размер окна, включающий, задан ли размер, или должен быть определен из определенного размера содержимого WPF. The initial size of the window, which includes whether the size is specified or should be determined from the determined size of the WPF content.
Родительское окно. The parent window.
Объект, HwndSourceHook включаемый в цепочку оконных процедур. The HwndSourceHook to include in the window procedure chain. При указании обработчика во время создания он получает все сообщения для окна. If you specify a hook at construction time, it receives all messages for the window. Можно использовать AddHook для добавления обработчика после создания окна. You can use AddHook to add a hook after the window is created.
Параметры прозрачности. The transparency settings. Окно верхнего уровня можно настроить для смешения с другими окнами на рабочем столе в соответствии с прозрачностью содержимого WPF для каждого пикселя. A top-level window can be configured to blend with the other windows on the desktop according to the per-pixel transparency of the WPF content. Чтобы включить эту функцию, задайте UsesPerPixelOpacity для свойства в HwndSourceParameters значение true . To enable this, set the UsesPerPixelOpacity property in the HwndSourceParameters to true . Это свойство может быть задано только во время создания и только с помощью HwndSource(HwndSourceParameters) сигнатуры конструктора и накладывает несколько ограничений. This property can only be specified at construction time, and only through the HwndSource(HwndSourceParameters) constructor signature, and it imposes several limitations.
После заполнения HwndSourceParameters структуры передайте ее в HwndSource(HwndSourceParameters) конструктор для HwndSource . After you populate the HwndSourceParameters structure, pass it to the HwndSource(HwndSourceParameters) constructor for the HwndSource.
Время жизни объекта Object Lifetime
HwndSourceЯвляется обычным объектом среды CLR, и его время существования управляет сборщиком мусора. An HwndSource is a regular common language runtime (CLR) object, and its lifetime is managed by the garbage collector. Поскольку HwndSource представляет неуправляемый ресурс, HwndSource реализует IDisposable . Because the HwndSource represents an unmanaged resource, HwndSource implements IDisposable. Синхронный вызов Dispose немедленно уничтожает окно Win32, если оно вызывается из потока владельца. Synchronously calling Dispose immediately destroys the Win32 window if called from the owner thread. При вызове из другого потока окно Win32 уничтожается асинхронно. If called from another thread, the Win32 window is destroyed asynchronously. DisposeДля некоторых сценариев взаимодействия может потребоваться явный вызов из взаимодействия кода. Calling Dispose explicitly from the interoperating code might be necessary for certain interoperation scenarios.
Процедуры окна Window Procedures
HwndSourceКласс реализует свою собственную процедуру окна. The HwndSource class implements its own window procedure. Эта процедура окна используется для обработки важных оконных сообщений, таких как связанные с макетом, отрисовкой и вводом. This window procedure is used to process important window messages, such as those related to layout, rendering, and input. Тем не менее можно также подключить процедуру окна для собственного использования. However, you can also hook the window procedure for your own use. Вы можете указать собственный обработчик во время построения, задав HwndSourceParameters.HwndSourceHook свойство, или можно также использовать AddHook и RemoveHook для добавления и удаления обработчиков после создания окна. You can specify your own hook during construction by setting the HwndSourceParameters.HwndSourceHook property, or you can also use AddHook and RemoveHook to add and remove hooks after the window is created. Обработчики вызываются по последнему первому порядку, что позволяет обработчикам выполняться перед встроенной обработкой. The hooks are called by last-in first-out order, which enables your hooks to execute before the built-in processing. Фактические обработчики удерживаются слабой ссылкой. The actual hooks are held by a weak reference. Поэтому убедитесь, что вы управляете временем существования делегата-обработчика. Therefore, make sure that you manage the lifetime of your hook delegate.
Дополнительные сведения о HwndSource и других классах взаимодействия см. в разделе взаимодействие WPF и Win32. For more information about HwndSource and other interoperation classes, see WPF and Win32 Interoperation.
Обратите внимание, что конструкторы HwndSource принимают параметры, похожие на параметры для функций Win32, таких как CreateWindowEx. Notice how the constructors for HwndSource take parameters that resemble the parameters for Win32 functions such as CreateWindowEx.
Преобразования масштаба не следует применять к RootVisual HwndSource . Scale transformations should not be applied to the RootVisual of an HwndSource. См. раздел Примечания для RootVisual . See Remarks for RootVisual.
Конструкторы
Инициализирует новый экземпляр класса HwndSource, используя структуру, содержащую начальные установки. Initializes a new instance of the HwndSource class by using a structure that contains the initial settings.
Инициализирует новый экземпляр класса HwndSource, используя заданные стиль класса, стиль, расширенный стиль, позицию x-y, ширину, высоту, имя и родительское окно. Initializes a new instance of the HwndSource class with a specified class style, style, extended style, x-y position, width, height, name, and parent window.
Инициализирует новый экземпляр класса HwndSource, используя заданные стиль класса, стиль, расширенный стиль, позицию x-y, ширину, высоту, имя, родительское окно и значение, указывающее, должен ли размер окна определяться автоматически. Initializes a new instance of the HwndSource class with a specified class style, style, extended style, x-y position, width, height, name, and parent window, and by specifying whether the window is autosized.
Инициализирует новый экземпляр класса HwndSource, используя заданные стиль класса, стиль, расширенный стиль, позицию x-y, имя и родительское окно. Initializes a new instance of the HwndSource class with a specified class style, style, extended style, x-y position, name, and parent window.
Свойства
Получает значение, определяющее, нужно ли получать фокус Win32 для содержащего окно WPF для данного объекта HwndSource. Gets the value that determines whether to acquire Win32 focus for the WPF containing window for this HwndSource.
Получает последовательность зарегистрированных приемников ввода. Gets a sequence of registered input sinks.
Возвращает наглядный диспетчер размещенного окна. Gets the visual manager for the hosted window.
Получает или задает значение AcquireHwndFocusInMenuMode для новых экземпляров HwndSource. Gets or sets the default AcquireHwndFocusInMenuMode value for new instances of HwndSource.
Возвращает объект Dispatcher, с которым связан этот объект DispatcherObject. Gets the Dispatcher this DispatcherObject is associated with.
(Унаследовано от DispatcherObject)
Возвращает дескриптор окна для данного HwndSource. Gets the window handle for this HwndSource.
Возвращает значение, показывающее, выполнена ли отмена Dispose() для данного HwndSource. Gets a value that indicates whether Dispose() has been called on this HwndSource.
Возвращает или задает указатель на интерфейс IKeyboardInputSite контейнера компонента. Gets or sets a reference to the component’s container’s IKeyboardInputSite interface.
Получает режим RestoreFocusMode для окна. Gets the RestoreFocusMode for the window.
Получает или задает свойство RootVisual окна. Gets or sets the RootVisual of the window.
Возвращает или задает значение, указывающее, как выполняется изменение размера окна в соответствии с его содержимым. Get or sets whether and how the window is sized to its content.
Возвращает значение, указывающее, учитывается ли значение непрозрачности каждого пикселя содержимого исходного окна. Gets a value that declares whether the per-pixel opacity of the source window content is respected.
Методы
Добавляет обработчик событий, получающий все сообщения окна. Adds an event handler that receives all window messages.
Добавляет экземпляр производного класса PresentationSource в список известных источников презентаций. Adds a PresentationSource derived class instance to the list of known presentation sources.
(Унаследовано от PresentationSource)
Определяет, имеет ли вызывающий поток доступ к этому DispatcherObject. Determines whether the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
Задает для списка прослушивателей события ContentRendered значение null . Sets the list of listeners for the ContentRendered event to null .
(Унаследовано от PresentationSource)
Возвращает дескриптор окна для HwndSource. Gets the window handle for the HwndSource. Дескриптор окна упаковывается как часть структуры HandleRef. The window handle is packaged as part of a HandleRef structure.
Освобождает все управляемые ресурсы, используемые объектом HwndSource, и порождает событие Disposed. Releases all managed resources that are used by the HwndSource, and raises the Disposed event.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Возвращает объект HwndSource заданного окна. Returns the HwndSource object of the specified window.
Возвращает визуальный целевой объект окна. Gets the visual target of the window.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Возвращает значение, указывающее, имеет ли приемник или один из содержащихся в нем компонентов фокус ввода. Gets a value that indicates whether the sink or one of its contained components has focus.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывается, когда значение DPI будет изменяться для окна. Called when the DPI is going to change for the window.
Вызывается, когда нажата одна из мнемоник (клавиш доступа) данного приемника. Called when one of the mnemonics (access keys) for this sink is invoked.
Регистрирует интерфейс IKeyboardInputSink размещенного компонента. Registers the IKeyboardInputSink interface of a contained component.
Удаляет обработчики событий, добавленные методом AddHook(HwndSourceHook). Removes the event handlers that were added by AddHook(HwndSourceHook).
Удаляет экземпляр производного класса PresentationSource из списка известных источников презентаций. Removes a PresentationSource derived class instance from the list of known presentation sources.
(Унаследовано от PresentationSource)
Обеспечивает уведомление об изменении корневого объекта Visual. Provides notification that the root Visual has changed.
(Унаследовано от PresentationSource)
Устанавливает фокус на первую или последнюю позицию табуляции приемника. Sets focus on either the first tab stop or the last tab stop of the sink.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Обрабатывает ввод с клавиатуры на уровне сообщений о нажатии клавиши. Processes keyboard input at the key-down message level.
Обрабатывает входные сообщения WM_CHAR, WM_SYSCHAR, WM_DEADCHAR и WM_SYSDEADCHAR перед вызовом метода OnMnemonic(MSG, ModifierKeys). Processes WM_CHAR, WM_SYSCHAR, WM_DEADCHAR, and WM_SYSDEADCHAR input messages before the OnMnemonic(MSG, ModifierKeys) method is called.
Обеспечивает наличие у вызывающего потока доступ к этому DispatcherObject. Enforces that the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
События
Генерируется, когда структура инициирует автоматическое изменение размера HwndSource. Occurs when layout causes the HwndSource to automatically resize.
Происходит, когда содержимое отрисовано и готово к взаимодействию с пользователем. Occurs when content is rendered and ready for user interaction.
(Унаследовано от PresentationSource)
Генерируется при вызове метода Dispose() данного объекта. Occurs when the Dispose() method is called on this object.
Создается при изменении разрешения монитора Hwnd или перемещении Hwnd на монитор с отличным разрешением (в точках на дюйм). Occurs when the DPI of the monitor of this Hwnd has changed, or the Hwnd is moved to a monitor with a different DPI.
Происходит при изменении значения свойства SizeToContent. Occurs when the value of the SizeToContent property changes.
Явные реализации интерфейса
Описание этого члена см. в разделе IList.Remove(Object). For a description of this member, see IList.Remove(Object).
Описание этого члена см. в разделе KeyboardInputSite. For a description of this member, see KeyboardInputSite.
Описание этого члена см. в разделе OnMnemonic(MSG, ModifierKeys). For a description of this member, see OnMnemonic(MSG, ModifierKeys).
Описание этого члена см. в разделе TabInto(TraversalRequest). For a description of this member, see TabInto(TraversalRequest).
Описание этого члена см. в разделе TranslateChar(MSG, ModifierKeys). For a description of this member, see TranslateChar(MSG, ModifierKeys).