2012-04-24 125 views

回答

24

OPTION 1

IWin32Window只需要一个Handle的性质,因为你已经有了的IntPtr这是不是太难以实施。 Create a wrapper类,它实现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; 
} 

你会再得到你IWin32Window这样的:

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

或(响应KeithS”建议):

IWin32Window win32Window = new WindowWrapper(this); 

OPTION 2 (thx to Scott Chamberlain的评论)

使用现有的实现IWin32Window的NativeWindow类:

IWin32Window win32Window = new NativeWindow(); 
((NativeWindow)win32Window).AssignHandle(new WindowInteropHelper(this).Handle); 
+0

很好的回答;该类可能会接受一个Window并处理第一层WindowInteropHelper包装,所以您只需要“新的WindowWrapper(this)”,并且您有一些东西可以作为IWin32Window传入。 – KeithS 2015-04-11 01:56:51

+3

而不是制作自己的类.NET在其[NativeWindow'](https://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow%28v=vs)中已经提供了类似的类。 110%29.aspx)课程。只需调用['AssignHandle(IntPtr)'](https://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow.assignhandle(v = vs.110).aspx)由OP提供的功能。 – 2015-04-16 04:28:46

+0

我无法获得选项2编译。我的代码... 'System.Windows.Forms.IWin32Window win32Window = new System.Windows.Forms.NativeWindow(); win32Window.AssignHandle(new WindowInteropHelper(this).Handle);' ...导致编译错误“IWin32Window不包含AssignHandle的定义”。我尝试使用IWin32Window的System.Windows.Interop版本,但没有NativeWindow()方法。 – 2017-12-28 15:27:04