c# - 如果表单没有焦点,则不会调用 OnPaint

标签 c# winforms

我有一个自定义绘画的用户控件。据我所知,构造函数正确设置样式。基本代码:

public partial class LineChart2 : UserControl
{
    public LineChart2()
    {
        InitializeComponent();

        //Set control styles to eliminate flicker on redraw and to redraw on resize
        this.SetStyle(
            ControlStyles.ResizeRedraw |
            ControlStyles.UserPaint |
            ControlStyles.AllPaintingInWmPaint |
            ControlStyles.DoubleBuffer,
            true);

        SetDefaultValues();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
    // breakpoint set here for verification
        Paint~misc stuff(e.Graphics);

        base.OnPaint(e);
    }

    private void UpdateGraph()
    {
    // this is called when the data that the control depends on changes
        ~update stuff();

        this.Invalidate();
        //this.Refresh();
    }
}

该控件包含在标准 WinForm 的面板中。

我已经尝试过 Invalidate 和 Refresh。

当使用 Invalidate() 时,只要控件所在的窗体具有焦点,控件就会正确重绘。绘图很流畅。当我将焦点切换到另一种形式时,即使事件仍在触发,绘图也会停止,并且 this.Invalidate() 仍在被调用。该表单在屏幕上仍然完全可见。

当使用Refresh()时,无论窗体是否有焦点,控件都会重绘,但绘图不断闪烁,好像绕过了双缓冲机制。

那么,无论焦点如何,如何获取 Invalidate 消息以正确调用 OnPaint 方法?

最佳答案

Documentation说:

Calling the Invalidate method does not force a synchronous paint; to force a synchronous paint, call the Update method after calling the Invalidate method.

您是否尝试过在 Invalidate 之后调用 Update

关于c# - 如果表单没有焦点,则不会调用 OnPaint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6157263/

相关文章:

c# - Java 枚举类型的 C# 等效项是什么?引用下面的代码

c# - RibbonControlsLibrary - 如何禁用最小化?

c# - 将数字代码复制到剪贴板并粘贴到 Excel,无需将其格式化为数字

c# - 允许操作访问共享上下文(例如 WCF 中的 OperationContext)

c# - 摆脱控制台命令行

c# - 如何在子窗体处于事件状态时禁用父窗体?

c# - 无法将基类转换为派生类

c# - mvc3 应用程序中的 RDLC 报告

c# - 从 Control 派生但隐藏属性

c# - ServiceInstaller 在 .NET 3.5+ 中是否已过时