对于组合框使用的NativeWindow会导致异常的处置法(Use of NativeWindow

2019-09-24 07:27发布

在C#中Windows.Forms的我想拦截糊windowmessage对于ComboBox。 由于这种不通过重载组合框的的WndProc法,因为我需要重写组合框里面的文本框的工作的WndProc,我决定创建一个自定义的类类型的NativeWindow其覆盖的WndProc。 我给你的手柄并释放它,当组合框手柄被摧毁。 但是,当处置的组合框被称为问题是,我得到一个InvalidOperationException说,一个无效的跨线程操作发生和组合框从比它创建的线程以外的线程访问。 任何想法是怎么回事错在这里?

在下面你会看到,我的课怎么是这样的:

public class MyCustomComboBox : ComboBox
{
    private WinHook hook = null;

    public MyCustomComboBox()
        : base()
    {
        this.hook = new WinHook(this);
    }

    private class WinHook : NativeWindow
    {
        public WinHook(MyCustomComboBox parent)
        {
            parent.HandleCreated += new EventHandler(this.Parent_HandleCreated);
            parent.HandleDestroyed += new EventHandler(this.Parent_HandleDestroyed);
        }

        protected override void WndProc(ref Message m)
        {
            // do something

            base.WndProc(ref m);
        }

        private void Parent_HandleCreated(object sender, EventArgs e)
        {
            MyCustomComboBox cbx = (MyCustomComboBox)sender;

            this.AssignHandle(cbx.Handle);
        }

        private void Parent_HandleDestroyed(object sender, EventArgs e)
        {
            this.ReleaseHandle();
        }
    }
}

Answer 1:

每汉斯的建议,我修改为使用代码CB_GETCOMBOBOXINFO从他自己的例子之一。

public class PastelessComboBox : ComboBox {

    private class TextWindow : NativeWindow {
      [StructLayout(LayoutKind.Sequential)]
      private struct RECT {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
      }

      private struct COMBOBOXINFO {
        public Int32 cbSize;
        public RECT rcItem;
        public RECT rcButton;
        public int buttonState;
        public IntPtr hwndCombo;
        public IntPtr hwndEdit;
        public IntPtr hwndList;
      }

      [DllImport("user32.dll", EntryPoint = "SendMessageW", CharSet = CharSet.Unicode)]
      private static extern IntPtr SendMessageCb(IntPtr hWnd, int msg, IntPtr wp, out COMBOBOXINFO lp);

      public TextWindow(ComboBox cb) {
        COMBOBOXINFO info = new COMBOBOXINFO();
        info.cbSize = Marshal.SizeOf(info);
        SendMessageCb(cb.Handle, 0x164, IntPtr.Zero, out info);
        this.AssignHandle(info.hwndEdit);
      }

      protected override void WndProc(ref Message m) {
        if (m.Msg == (0x0302)) {
          MessageBox.Show("No pasting allowed!");
          return;
        }
        base.WndProc(ref m);
      }
    }

    private TextWindow textWindow;

    protected override void OnHandleCreated(EventArgs e) {
      textWindow = new TextWindow(this);
      base.OnHandleCreated(e);
    }

    protected override void OnHandleDestroyed(EventArgs e) {
      textWindow.ReleaseHandle();
      base.OnHandleDestroyed(e);
    }

  }


文章来源: Use of NativeWindow for ComboBox causes exception in Dispose-method