How to set window owner to an unmanaged window

2019-08-10 02:44发布

I want to set the owner form to that of an unamanged window. I have the unmanaged window's handle. How can I set this unmanaged window to be the owner window for my managed form?

IntPtr hWnd = GetUnmanagedWindow();//assume the handle is returned correctly
Form form = new Form();
form.Show(ConvertToManaged(hWnd));//Need an implementation for ConvertOrSomething()

2条回答
唯我独甜
2楼-- · 2019-08-10 03:28

The standard way to do this is to use the NativeWindow class.

IntPtr hWnd = GetUnmanagedWindow();//assume the handle is returned correctly
Form form = new Form();
NativeWindow nativeWindow = new NativeWindow();
nativeWindow.AssignHandle(hWnd);
form.Show(nativeWindow);

As Hans points out, remember to call ReleaseHandle when are done with it.

查看更多
唯我独甜
3楼-- · 2019-08-10 03:35
public ManagedWindow ConvertToManaged(IntPtr hWnd)
{
   return new ManagedWindow(hWnd);
}

    public class ManagedWindow : IWin32Window
    {
        IntPtr _handle;
        public IntPtr Handle
        {
            get { return _handle; }
        }

        public ManagedWindow(IntPtr handle)
        {
            _handle = handle;
        }
    }
查看更多
登录 后发表回答