Control.Invalidate不会触发隐藏或不可见控件

时间:2016-07-01 05:26:49

标签: c# winforms paint invalidation

当我在隐藏或不可见控件上调用Invalidate方法时,不会触发绘制事件。

这是Windows窗体控件的行为吗?有没有可用的文件?

我查看了Control.Invalidate方法的文档,但没有提到隐形控件 https://msdn.microsoft.com/en-in/library/system.windows.forms.control.invalidated(v=vs.110).aspx

我检查了以下SO问题How are the painting of invisible controls handled in WinForms?,但在紧凑框架中询问是否存在闪烁问题,与我的问题无关

1 个答案:

答案 0 :(得分:4)

我认为调查此问题的最佳方法是检查Microsoft的源代码。这是正在发生的事情:

Control设置为Visible false时,Control的句柄创建标志也会设置为false

Invalidate()为false时,IsHandleCreated方法(下面的源代码)无法正常工作;这实际上就是整个故事。

/// <include file='doc\Control.uex' path='docs/doc[@for="Control.Invalidate3"]/*' />
/// <devdoc>
///     Invalidates the control and causes a paint message to be sent to the control.
///     This will not force a synchronous paint to occur, calling update after
///     invalidate will force a synchronous paint.
/// </devdoc>
public void Invalidate(bool invalidateChildren)
{
    if (IsHandleCreated)
    {
        if (invalidateChildren)
        {
            SafeNativeMethods.RedrawWindow(new HandleRef(window, Handle),
                                            null, NativeMethods.NullHandleRef,
                                            NativeMethods.RDW_INVALIDATE |
                                            NativeMethods.RDW_ERASE |
                                            NativeMethods.RDW_ALLCHILDREN);
        }
        else
        {
            // It's safe to invoke InvalidateRect from a separate thread.
            using (new MultithreadSafeCallScope())
            {
                SafeNativeMethods.InvalidateRect(new HandleRef(window, Handle),
                                                    null,
                                                    (controlStyle & ControlStyles.Opaque) != ControlStyles.Opaque);
            }
        }

        NotifyInvalidate(this.ClientRectangle);
    }
}