Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

c# - Get System.Windows.Forms.IWin32Window from WPF window

I'm writing a WPF app, and I'd like to make use of this library.

I can get an IntPtr for the window by using

new WindowInteropHelper(this).Handle

but that won't cast to System.Windows.Forms.IWin32Window, which I need to show this WinForms dialog.

How do I cast IntPtr to System.Windows.Forms.IWin32Window?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OPTION 1

IWin32Window only expects a Handle property, which is not too difficult to implement since you already have the IntPtr. Create a wrapper class that implements IWin32Window:

public class WindowWrapper : System.Windows.Forms.IWin32Window
{
    public WindowWrapper(IntPtr handle)
    {
        _hwnd = handle;
    }

    public WindowWrapper(Window window)
    {
        _hwnd = new WindowInteropHelper(window).Handle;
    }

    public IntPtr Handle
    {
        get { return _hwnd; }
    }

    private IntPtr _hwnd;
}

You would then get your IWin32Window like this:

IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle);

or (in response to KeithS' suggestion):

IWin32Window win32Window = new WindowWrapper(this);

OPTION 2 (thx to Scott Chamberlain's comment)

Use the existing NativeWindow class, which implements IWin32Window:

NativeWindow win32Parent = new NativeWindow();
win32Parent.AssignHandle(new WindowInteropHelper(this).Handle);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...