gpt4 book ai didi

c# - 将 NativeWindow 用于 ComboBox 会导致 Dispose 方法出现异常

转载 作者:行者123 更新时间:2023-11-30 15:37:07 25 4
gpt4 key购买 nike

在 C# Windows.Forms 中,我想拦截组合框的粘贴窗口消息。因为这不能通过覆盖组合框的 WndProc 方法来工作,因为我需要覆盖组合框内文本框的 WndProc,所以我决定创建一个 NativeWindow 类型的自定义类来覆盖 WndProc。当组合框句柄被破坏时,我分配句柄并释放它。但是当组合框的 Dispose 被调用时,问题是我得到一个 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();
}
}
}

最佳答案

根据 Hans 的建议,我修改了代码以使用 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);
}

}

关于c# - 将 NativeWindow 用于 ComboBox 会导致 Dispose 方法出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12976115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com