Introduction
If we need to use the functions under Windows Forms namespace
, we may come across the problem regarding different window handles. How to convert from System.Window
handle in WPF to IWin32Window
in Windows Forms is what we need to solve in this article.
Background
Here, we just create an example. Windows Forms message box is called by a thread in WPF and modal state is necessary. In this case, IWin32Window
handle is required to set the current main window.
In a general Windows Forms application, there is a function named MessageBox.Show
which could pop up a message box with different styles.
The following MessageBoxButton
s constants are defined in System.Windows.Forms
:
Member Name |
Description |
AbortRetryIgnore |
The message box contains Abort, Retry, and Ignore buttons. |
OK |
The message box contains an OK button. |
OKCancel |
The message box contains OK and Cancel buttons. |
RetryCancel |
The message box contains Retry and Cancel buttons. |
YesNo |
The message box contains Yes and No buttons. |
YesNoCancel |
The message box contains Yes, No, and Cancel buttons. |
In WPF Windows namespace
, there is a function named MessageBox.Show
as well. However, it has different style definitions.
The following MessageBoxButton
constants are defined under System.Windows
:
Member name |
Description |
OK |
The message box displays an OK button. |
OKCancel |
The message box displays OK and Cancel buttons. |
OKCancel |
The message box displays Yes and No buttons. |
YesNoCancel |
The message box displays Yes, No, and Cancel buttons. |
But sometimes, the styles such as AbortRetryIgnore
style message box is quite useful in application development. But if we need to use the message box in Windows Forms with modal state in a multi-threading model, the IWin32Window
handle is required instead of a WPF window handle.
Using the Code
The following code could help us get IWin32Window
from a WPF application.
Firstly, we could get a Windows handle as an InPtr
from process
. After that, we need a WindowWrapper
to convert the window handle into IWin32Window
.
string strFriendlyName = AppDomain.CurrentDomain.FriendlyName;
Process[] pro = Process.GetProcessesByName(
strFriendlyName.Substring(0, strFriendlyName.LastIndexOf('.')));
System.Windows.Forms.MessageBox.Show(
new WindowWrapper(pro[0].MainWindowHandle),
"Warning Message.", "Title",
MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning);
public class WindowWrapper : System.Windows.Forms.IWin32Window
{
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
private IntPtr _hwnd;
}
History
- 5th September, 2007: Initial post