0

We sporadically get errors when we try to update a tool tip, like this

ToolTip.SetToolTip(myLabel, customDataStructure)

The error we get is a NullReferenceException: Object reference not set to an instance of an object

Does anyone know the cause of this?

Is a simple Try/Catch that eats the NullReferenceException a feasible option? We don't want our entire application to blow up when we get this.

4

5 回答 5

1

Try to test whether you're setting that var in any situation, using the debugger for example...

Is a simple Try/Catch that eats the NullReferenceException a feasible option?

That wouldn't solve the problem, it would hide it. A bad programming practice.

于 2009-05-05T20:00:48.320 回答
1

Ignoring exceptions is rarely if ever a good idea. The exception is thrown because something is wrong in the current implementation. By ignoring the exception the application basically proceeds in an undefined state and you will most likely see other weird effects due to the missing reference.

Since this is sporadic it could be a race condition issue, so you have to look carefully at the code to figure out if there are any situations in which the reference may be used before it is correctly initialized.

于 2009-05-05T20:01:58.863 回答
1

我猜您是ToolTip.SetTooltip从事件处理程序调用的,并且该处理程序有时会在创建标签之前触发。您可能应该通过检查标签来保护这一点,null然后确保在标签Load事件上初始化工具提示。

您当然不应该只捕获异常,因为这隐藏了问题。

于 2009-05-05T20:08:33.667 回答
1

造成这种情况的最常见原因是当您关闭窗口并发生在不可见控件上设置工具提示的验证时。

我还没有调试到 .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处理的事情......

于 2016-01-04T02:08:33.027 回答
0

我刚刚遇到了同样的问题。似乎异常是从 ToolTip.CreateHandle() 方法中引发的,并且它仅发生在被释放的 MDI 子窗口上。在调用 SetToolTip(...) 方法之前,请确保父窗体的 Disposing 属性为 false。无论如何,表单正在被处理,所以你不再关心工具提示了......

于 2009-08-12T13:48:38.340 回答