- Native Window Класс
- Определение
- Примеры
- Form. Show(IWin32Window) Метод
- Определение
- Параметры
- Исключения
- Комментарии
- C# WinForms: Form.ShowDialog() with IWin32Window owner parameter in a different thread
- Tool Tip. Show Метод
- Определение
- Перегрузки
- Show(String, IWin32Window, Int32, Int32)
- Параметры
- Комментарии
- Should Form.ShowDialog(IWin32Window) work with any window handle?
Native Window Класс
Определение
Обеспечивает низкоуровневую инкапсуляцию дескриптора окна и процедуры окна. Provides a low-level encapsulation of a window handle and a window procedure.
Примеры
В следующем примере кода показано перехват сообщений окна операционной системы в процедуре окна и создание окна с заданным именем класса окна операционной системы. The following code example demonstrates intercepting operating system window messages in a window procedure, and creating a window with a specific operating system window class name. В примере создаются два класса, которые наследуются от этого NativeWindow . The example creates two classes that inherit from NativeWindow that accomplish this.
Класс подключается к MyNativeWindowListener процедуре окна формы, передаваемой в конструктор, и переопределяет WndProc метод для перехвата WM_ACTIVATEAPP сообщения окна. The MyNativeWindowListener class hooks into the window procedure of the form passed into the constructor, and overrides the WndProc method to intercept the WM_ACTIVATEAPP window message. Класс демонстрирует использование AssignHandle ReleaseHandle методов и для задания обрабатываемого окна NativeWindow . The class demonstrates the usage of the AssignHandle and ReleaseHandle methods to identify the window handle the NativeWindow will use. Этот маркер назначается на основе Control.HandleCreated событий и Control.HandleDestroyed . The handle is assign based upon the Control.HandleCreated and Control.HandleDestroyed events. Когда WM_ACTIVATEAPP получено сообщение окна, класс вызывает form1.ApplicationActivated метод. When the WM_ACTIVATEAPP window message is received, the class calls the form1.ApplicationActivated method.
MyNativeWindow Класс создает новое окно с параметром, имеющим ClassName значение BUTTON . The MyNativeWindow class creates a new window with the ClassName set to BUTTON . Класс демонстрирует использование CreateHandle метода и переопределение WndProc метода для перехвата полученных сообщений окна. The class demonstrates using the CreateHandle method and overriding the WndProc method to intercept window messages that are received.
Form. Show(IWin32Window) Метод
Определение
Показывает форму с указанным владельцем. Shows the form with the specified owner to the user.
Параметры
Любой объект, который реализует IWin32Window, представляющий окно верхнего уровня, которое станет владельцем этой формы. Any object that implements IWin32Window and represents the top-level window that will own this form.
Исключения
Отображаемая форма уже отображена. The form being shown is already visible.
-или- -or- Форма, указанная в параметре owner , совпадает с отображаемой формой. The form specified in the owner parameter is the same as the form being shown.
-или- -or- Отображаемая форма отключена. The form being shown is disabled.
-или- -or- Отображаемая форма не является окном верхнего уровня. The form being shown is not a top-level window.
-или- -or- Отображаемая в виде диалогового окна форма уже является модальной формой. The form being shown as a dialog box is already a modal form.
-или- -or- Текущий процесс не выполняется в интерактивном пользовательском режиме (дополнительные сведения см. в описании свойства UserInteractive). The current process is not running in user interactive mode (for more information, see UserInteractive).
Комментарии
Этот метод можно использовать для вывода не модальной формы. You can use this method to display a non-modal form. При использовании этого метода Owner свойство формы устанавливается в значение owner . When you use this method, the Owner property of the form is set to owner . Немодальная форма может использовать Owner свойство для получения сведений о форме-владельце. The non-modal form can use the Owner property to get information about the owning form. Вызов этого метода идентичен заданию Owner Свойства немодального объекта и последующему вызову Show() метода. Calling this method is identical to setting the Owner property of the non-modal and then calling the Show() method.
Отображение формы эквивалентно присвоению Visible свойству значения true . Showing the form is equivalent to setting the Visible property to true . После Show вызова метода Visible свойство возвращает значение true до тех пор, пока Hide не будет вызван метод. After the Show method is called, the Visible property returns a value of true until the Hide method is called.
C# WinForms: Form.ShowDialog() with IWin32Window owner parameter in a different thread
I am creating a C# VSTO addin and am having trouble with setting the owner window parameter in Form.ShowDialog() when the form is shown in a secondary thread and the owner window is on the main thread.
When using VSTO, Excel only supports changes to the Excel object model on the main thread (it can be done on a separate thread but is dangerous and will throw COM exceptions if Excel is busy). I would like to show a progress form while executing a long operation. To make the progress form fluid, I show the form on a separate thread and update the progress asynchronously from the main thread using Control.BeginInvoke(). This all works fine, but I seem to only be able to show the form using Form.ShowDialog() with no parameters. If I pass an IWin32Window or NativeWindow as a parameter to ShowDialog, the form freezes up and does not update the progress. This may be because the owner IWin32Window parameter is a Window that exists on the main thread and not the secondary thread that the progress form is displayed on.
Is there any trick I can try to pass a IWin32Window to the ShowDialog function when the form is on a separate thread. Technically I don’t need to set the form’s owner, but rather the form’s parent if there is such a difference.
I’d like my dialog to be linked with the Excel Window so that when Excel is minimized or maximized, the dialog will be hidden or shown accordingly.
Please note that I have already tried going the BackgroundWorker route and it was not successful for what I was trying to accomplish.
—-Updated with sample code:
Below is a trimmed down version of what I am trying to do and how I am trying to do it. The MainForm is not actually used in my application, as I am trying to use it to represent the Excel Window in a VSTO application.
Tool Tip. Show Метод
Определение
Задает текст всплывающей подсказки, а затем отображает ее. Sets the text associated with a ToolTip, and then displays it.
Перегрузки
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в модальном режиме в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip modally at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в течение указанного времени в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в течение указанного времени в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в модальном режиме в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip modally at the specified relative position.
Задает текст всплывающей подсказки, связанный с указанным элементом управления, и отображает всплывающую подсказку в модальном режиме. Sets the ToolTip text associated with the specified control, and displays the ToolTip modally.
Задает текст всплывающей подсказки, связанный с указанным элементом управления, а затем отображает всплывающую подсказку в течение заданного времени. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration.
Show(String, IWin32Window, Int32, Int32)
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в модальном режиме в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip modally at the specified relative position.
Параметры
Строка String, содержащая новый текст всплывающей подсказки. A String containing the new ToolTip text.
Элемент управления Control, для которого отображается всплывающая подсказка. The Control to display the ToolTip for.
Смещение по горизонтали в пикселях относительно верхнего левого угла окна связанного элемента управления для отображения всплывающей подсказки. The horizontal offset, in pixels, relative to the upper-left corner of the associated control window, to display the ToolTip.
Смещение по вертикали в пикселях относительно верхнего левого угла окна связанного элемента управления для отображения всплывающей подсказки. The vertical offset, in pixels, relative to the upper-left corner of the associated control window, to display the ToolTip.
Комментарии
Эта версия перегруженного Show метода работает идентично Show(String, IWin32Window, Point) версии, за исключением того, что смещение задается как отдельные координаты x и y вместо Point . This version of the overloaded Show method operates identically to the Show(String, IWin32Window, Point) version, except that the offset is specified as separate x- and y-coordinates instead of a Point.
Приложения, работающие в режиме частичного доверия, должны утверждать AllWindows разрешение на использование этого метода, а также Show управлять отображением и расположением подсказки, независимо от действия пользователя. Applications running in partial trust must assert the AllWindows permission to use this method, as Show can control the display and location of a ToolTip independent of user action.
Should Form.ShowDialog(IWin32Window) work with any window handle?
When using System.Windows.Forms.ShowDialog(IWin32Window) , should I be able to pass in an IWin32Window representing any window handle and have it be modal with respect to that window?
As part of an Internet Explorer 7 extension I’m trying to open a window modal with respect to an Internet Explorer tab. It’s not the currently selected tab, but I can get the hwnd of the tab OK. However, when I pass this to ShowDialog my Form is shown, but it’s not modal with respect to anything: I can still do things in Internet Explorer, including in the tab that’s supposed to be the owner. My form is shown floating above the Internet Explorer windows and it stays on top, so it’s not like it’s just opened as a normal form, but it’s not correctly modal.
Using Spy++, I can find my form and it’s owner handle is correctly set.
Does this mean that something has gone wrong, or I’m doing something wrong? How do I make my form correctly modal?
FYI, I’m using this wrapper class to create an IWin32Window from a hwnd (thanks Ryan!):
UPDATE: Using Internet Explorer 7 & .NET 2.0
UPDATE: Playing around some more with Spy++ and the handles it exposes, I find that if I use a different hwnd then I can make my window modal to the tab:
I was using the tab’s hwnd as suggested by the IWebBrowser2.HWND doc, which in Spy++ appears as class TabWindowClass . It has a child of class Shell DocObject View , which has a child of Internet_Explorer_Server. If I use the hwnd of the Internet Explorer_Server then it works correctly, for example, when I click with the mouse on other tabs, Internet Explorer reacts normally. When I click with the mouse on the tab of interest, it plays the windows d’oh sound and doesn’t do anything.
I don’t yet know how to programatically get the Internet_Explorer_Server hwnd , but it should be possible.
Also, for what it’s worth, while playing with other window handles I was generally able to make my form modal to other applications and dialogs. So I guess the answer to my question is ‘many but not all handles’. possibly it depends on the application?