具有启用/禁用功能的WPF WinForms Interop问题 [英] WPF WinForms Interop issue with Enable / Disable

查看:109
本文介绍了具有启用/禁用功能的WPF WinForms Interop问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WinForms用户控件,其中托管了WPF自定义列表框. WinForms用户控件被禁用,然后重新启用后,WinForms用户控件中的WPF控件将无响应.其他人有没有经历过?

I have a WinForms usercontrol hosting a WPF custom Listbox in it. After the WinForms user control gets disabled and then re-enabled the WPF control in the WinForms usercontrol is unresponsive. Has anyone else experienced this?

每当控件被禁用/启用以解决此问题时,我们都必须深情地删除并重新添加元素主机.

We had to hack a soultion into remove and re-add the element host each time the control gets disable / enabled to fix the issue.

wpfControl.Enabled = false;
...
wpfControl.Enabled = true;

在用于用户控件的WinForms EnabledChanged方法中修复该缺陷的方法

Hack for fixing it in the WinForms EnabledChanged method for the usercontrol

if ( Enabled ) 
{
  ElementHost oldEh = ctlElementHost;
  ElementHost eh = new ElementHost();
  eh.Name = oldEh.Name;
  oldEh.Child = null;
  eh.Child = wpfControl;
  this.Controls.Remove( ctlElementHost );
  this.Controls.Add( eh );
  eh.Dock = DockStyle.Fill;

  oldEh.Dispose();
  ctlElementHost = eh;
}

似乎存在内存泄漏,其中放置元素的主机仍然停留在周围,直到托管WinForms用户控件的父窗体被关闭.

There seems to be a memory leak where the disposed element hosts are still sticking around until the parent form that was hosting the WinForms usercontrol gets closed.

推荐答案

我的一位同事(感谢KwB)设法找到了解决此问题的方法:

A co-worker (thanks KwB) of mine managed to find a fix for this issue: http://support.microsoft.com/kb/955753

它涉及从ElementHost继承并手动告诉窗口区域启用:

It involves inheriting from ElementHost and manually telling the window region to enable:

public class MyElementHost : ElementHost
{
    protected override void OnEnabledChanged(EventArgs e)
    {
        SynchChildEnableState(); 

        base.OnEnabledChanged(e);
    } 

    private void SynchChildEnableState()
    {
        IntPtr childHandle = GetWindow(Handle, GW_CHILD);
        if (childHandle != IntPtr.Zero)
        {
            EnableWindow(childHandle, Enabled);
        }
    } 

    private const uint GW_CHILD = 5; 

    [DllImport("user32.dll")]
    private extern static IntPtr GetWindow(IntPtr hWnd, uint uCmd); 

    [DllImport("user32.dll")]
    private extern static bool EnableWindow(IntPtr hWnd, bool bEnable);
} 

这篇关于具有启用/禁用功能的WPF WinForms Interop问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆