在 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();
}
}
}
根据汉斯的建议,我修改了代码以使用CB_GETCOMBOBOXINFO http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/e234c4a7-0cf7-4284-a072-8152f7593002来自他自己的一个例子。
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)