在C#
WinForm
桌面应用程序初始化中,我具有自定义的插入符号事件处理程序:
public Form1()
{
InitializeComponent();
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
}
然后textBox1_KeyDown
显示脱字号:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
ShowCaret(textBox1.Handle);
}
并且来自textBox1_TextChanged
:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
int x = 0;
DrawCaret(textBox1, x);
}
else if (textBox1.Text.Length < 1)
{
int x = 1;
DrawCaret(textBox1, x);
}
}
并且:
[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
void textBox1_GotFocus(object sender, EventArgs e)
{
int x = 1;
DrawCaret(textBox1, x);
}
int size;
public void DrawCaret(Control ctrl, int x)
{
if (x == 0) { size = 2; }
else { size = 15; }
var nHeight = textBox1.Height;
var nWidth = size;
nHeight = Font.Height;
CreateCaret(ctrl.Handle, IntPtr.Zero, nWidth, nHeight);
}
我得到:
System.ObjectDisposedException”发生在ShowCaret(ctrl.Handle);
哪个在代码行上显示异常:
CreateCaret(ctrl.Handle, IntPtr.Zero, nWidth, nHeight);
但附在上面的static extern bool ShowCaret(IntPtr hWnd);
上。
无法找出导致此异常的原因
任何指南,建议或示例都会有所帮助