Close child dialogs when closing the parent

前端 未结 1 1643
慢半拍i
慢半拍i 2021-01-18 11:18

I\'m writing a Windows shell extension in C# using EZShellExtensions.NET.

I contribute a context menu that shows dialogs.

Suppose that I show an Explorer wi

相关标签:
1条回答
  • 2021-01-18 11:41

    Finally I have implemented it in the following way. The dialog is shown using ShowDialog() but is launched (and created in a thread). ShowDialog() implements its own message loop, so as the form is launched in a thread, the main form respond to events, and also you can close the main form and the child form still respond to events. This is very useful for a ShellExtension application.

    Remember dispose all on your form, in order to free the thread, and also the shell extension thread (each shell extension window and childs are executed in a thread).

    The following code fixed my issue:

        protected virtual void SetupViewControl()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSetupViewControl));
    
            while (!mViewControlCreated)
            {
                // wait for view control created
                Thread.Sleep(100);
            }
        }
    
        private bool mViewControlCreated = false;
    
        protected virtual void DoSetupViewControl(object state)
        {
            mViewControl = ViewControlFactory.CreateViewControl();
    
            mViewControl.Dock = DockStyle.Fill;
            mViewControl.Initialize();
    
            this.Controls.Clear();
            this.Controls.Add(mViewControl);
    
            IntPtr wHnd = GetActiveWindow();
            IWin32Window owner = GetOwner(wHnd);
    
            mViewControlCreated = true;
    
            ShowDialog(owner);
    
            this.Dispose();
        }
    
        private IWin32Window GetOwner(IntPtr wHnd)
        {
            if (wHnd == IntPtr.Zero) return null;
    
            return new WindowWrapper(wHnd);
        }
    
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern IntPtr GetActiveWindow();
    
        private class WindowWrapper : IWin32Window
        {
            private IntPtr mHwnd;
    
            public WindowWrapper(IntPtr handle)
            {
                mHwnd = handle;
            }
    
            public IntPtr Handle
            {
                get { return mHwnd; }
            }
        }
    
    0 讨论(0)
提交回复
热议问题