造成这种情况的最常见原因是当您关闭窗口并发生在不可见控件上设置工具提示的验证时。
我还没有调试到 .Net 代码,但很清楚 ToolTip.CreateHandle 代码中错误所在的位置:
private void CreateHandle()
{
if (this.GetHandleCreated())
{
return;
}
IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate();
try
{
SafeNativeMethods.InitCommonControlsEx(new NativeMethods.INITCOMMONCONTROLSEX
{
dwICC = 8
});
CreateParams createParams = this.CreateParams;
if (this.GetHandleCreated())
{
return;
}
//HERE! I suspect window is null when the form is closed
this.window.CreateHandle(createParams);
}
finally
{
UnsafeNativeMethods.ThemingScope.Deactivate(userCookie);
}
if (this.ownerDraw)
{
int num = (int)((long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, this.Handle), -16));
num &= -8388609;
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, this.Handle), -16, new HandleRef(null, (IntPtr)num));
}
解决此问题的条件非常简单,只需在调用 ToolTip 控件的 SetToolTip 方法之前检查表单是否可见或 Benjamin RAIBAUD 提到 Disposing = false 即可:
C#:
if (!this.Disposing) ttpHoverText.SetToolTip(targetControl, brokenText);
VB.Net:
If Me.Disposing = False Then ttpHoverText.SetToolTip(targetControl, brokenText)
IMO这是应该由.Net Framework处理的事情......