OPTION 1
IWin32Window chỉ hy vọng một tài sản Handle
, mà không phải là quá khó khăn để thực hiện kể từ khi bạn đã có IntPtr. Create a wrapper lớp mà thực hiện 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;
}
Sau đó, bạn sẽ nhận được IWin32Window của bạn như thế này:
IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle);
hoặc (để đáp lại đề nghị KeithS'):
IWin32Window win32Window = new WindowWrapper(this);
OPTION 2 (thx nhận xét của Scott Chamberlain)
Sử dụng lớp NativeWindow hiện có, thực hiện IWin32Window:
IWin32Window win32Window = new NativeWindow();
((NativeWindow)win32Window).AssignHandle(new WindowInteropHelper(this).Handle);
Câu trả lời hay; các lớp học, mặc dù, có thể chấp nhận một cửa sổ và xử lý lớp đầu tiên của WindowInteropHelper gói là tốt, vì vậy tất cả bạn cần là 'new WindowWrapper (this)' và bạn có cái gì để vượt qua như là một IWin32Window. – KeithS
Thay vì tạo lớp của riêng bạn .NET cung cấp một lớp tương tự đã có trong [NativeWindow'] của nó (https://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow%28v=vs. 110% 29.aspx) lớp học. Chỉ cần gọi ['AssignHandle (IntPtr)'] (https://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow.assignhandle (v = vs.110) .aspx) với tay cầm từ chức năng do OP cung cấp. –
Tôi không thể nhận được Tùy chọn 2 để biên dịch. Mã của tôi ... 'System.Windows.Forms.IWin32Window win32Window = new System.Windows.Forms.NativeWindow(); win32Window.AssignHandle (new WindowInteropHelper (this) .Handle); ' ... dẫn đến lỗi biên dịch "IWin32Window không chứa định nghĩa cho AssignHandle". Tôi đã thử bằng cách sử dụng phiên bản System.Windows.Interop của IWin32Window nhưng không có phương thức NativeWindow(). –