- Form. Show(IWin32Window) Метод
- Определение
- Параметры
- Исключения
- Комментарии
- Convert an IntPtr window handle to IWin32Window^
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged c++-cli handle or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- C# WinForms: Form.ShowDialog() with IWin32Window owner parameter in a different thread
- Hwnd Source Class
- Definition
- Remarks
- Constructors
- Properties
- Methods
- Events
- Explicit Interface Implementations
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.
Convert an IntPtr window handle to IWin32Window^
How do I convert a handle acquired from a form/control’s Handle property, to a IWin32Window^ ?
3 Answers 3
(That gets you the Control object, which implements the IWin32Window interface.)
Note that this relies on the handle being «acquired from a form/control’s Handle property.» You cannot use this technique with an arbitrary Win32 window handle.
There’s a simpler method that is supported directly by the .NET framework without having to create your own custom class. You can use this with any arbitrary Window handle.
Given ptrWindowHandle of type IntPtr:
System.Windows.Forms.NativeWindow implements the IWin32Window interface.
This appears to be exactly what you are asking for. I’ve never done it myself, but it appears to be relatively straightforward:
Not the answer you’re looking for? Browse other questions tagged c++-cli handle or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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.
Hwnd Source Class
Definition
Presents Windows Presentation Foundation (WPF) content in a Win32 window.
Remarks
Many members of this class are unavailable in the Internet security zone.
An HwndSource implements a Win32 window that can contain WPF content. The WPF content in the window is arranged, measured, and rendered; and is interactive to input. 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.
Provide access to the window handle (HWND).
Destroy the window.
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. 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
Many aspects of the HwndSource can only be specified at construction time. 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. You must use PInvoke to change the styles after the window is created. Not all styles can be changed after the window is created. Consult the Win32 documentation before changing window styles.
The initial position of the window.
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.
The HwndSourceHook to include in the window procedure chain. If you specify a hook at construction time, it receives all messages for the window. You can use AddHook to add a hook after the window is created.
The transparency settings. 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. To enable this, set the UsesPerPixelOpacity property in the HwndSourceParameters to true . This property can only be specified at construction time, and only through the HwndSource(HwndSourceParameters) constructor signature, and it imposes several limitations.
After you populate the HwndSourceParameters structure, pass it to the HwndSource(HwndSourceParameters) constructor for the HwndSource.
Object Lifetime
An HwndSource is a regular common language runtime (CLR) object, and its lifetime is managed by the garbage collector. Because the HwndSource represents an unmanaged resource, HwndSource implements IDisposable. Synchronously calling Dispose immediately destroys the Win32 window if called from the owner thread. If called from another thread, the Win32 window is destroyed asynchronously. Calling Dispose explicitly from the interoperating code might be necessary for certain interoperation scenarios.
Window Procedures
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. 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.
For more information about HwndSource and other interoperation classes, see WPF and Win32 Interoperation.
Notice how the constructors for HwndSource take parameters that resemble the parameters for Win32 functions such as CreateWindowEx.
Scale transformations should not be applied to the RootVisual of an HwndSource. See Remarks for RootVisual.
Constructors
Initializes a new instance of the HwndSource class by using a structure that contains the initial settings.
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.
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.
Initializes a new instance of the HwndSource class with a specified class style, style, extended style, x-y position, name, and parent window.
Properties
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.
Gets or sets the default AcquireHwndFocusInMenuMode value for new instances of HwndSource.
Gets the Dispatcher this DispatcherObject is associated with.
(Inherited from DispatcherObject)
Gets the window handle for this HwndSource.
Gets a value that indicates whether Dispose() has been called on this HwndSource.
Gets or sets a reference to the component’s container’s IKeyboardInputSite interface.
Gets the RestoreFocusMode for the window.
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.
Methods
Adds an event handler that receives all window messages.
Adds a PresentationSource derived class instance to the list of known presentation sources.
(Inherited from PresentationSource)
Determines whether the calling thread has access to this DispatcherObject.
(Inherited from DispatcherObject)
Sets the list of listeners for the ContentRendered event to null .
(Inherited from PresentationSource)
Gets the window handle for the HwndSource. The window handle is packaged as part of a HandleRef structure.
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.
(Inherited from Object)
Returns the HwndSource object of the specified window.
Gets the visual target of the window.
Serves as the default hash function.
(Inherited from Object)
Gets the Type of the current instance.
(Inherited from Object)
Gets a value that indicates whether the sink or one of its contained components has focus.
Creates a shallow copy of the current Object.
(Inherited from Object)
Called when the DPI is going to change for the window.
Called when one of the mnemonics (access keys) for this sink is invoked.
Registers the IKeyboardInputSink interface of a contained component.
Removes the event handlers that were added by AddHook(HwndSourceHook).
Removes a PresentationSource derived class instance from the list of known presentation sources.
(Inherited from PresentationSource)
Provides notification that the root Visual has changed.
(Inherited from 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.
(Inherited from Object)
Processes keyboard input at the key-down message level.
Processes WM_CHAR, WM_SYSCHAR, WM_DEADCHAR, and WM_SYSDEADCHAR input messages before the OnMnemonic(MSG, ModifierKeys) method is called.
Enforces that the calling thread has access to this DispatcherObject.
(Inherited from DispatcherObject)
Events
Occurs when layout causes the HwndSource to automatically resize.
Occurs when content is rendered and ready for user interaction.
(Inherited from PresentationSource)
Occurs when the Dispose() method is called on this object.
Occurs when the DPI of the monitor of this Hwnd has changed, or the Hwnd is moved to a monitor with a different DPI.
Occurs when the value of the SizeToContent property changes.
Explicit Interface Implementations
For a description of this member, see IList.Remove(Object).
For a description of this member, see KeyboardInputSite.
For a description of this member, see OnMnemonic(MSG, ModifierKeys).
For a description of this member, see TabInto(TraversalRequest).
For a description of this member, see TranslateChar(MSG, ModifierKeys).