TableLayoutPanel responds very slowly to events

一曲冷凌霜 提交于 2019-11-26 16:46:59

问题


In my application I really needed to place a lot of controls (label, textbox, domainupdown) in a nice order. So I went ahead and used some nested TableLayoutPanel. The problem now is, this form responds very slow to most of events (resize, maximize, minimize and ...) it takes really up to 5 seconds for controls within the tables to get resized, redrawed to the new size of form.

I am putting a finger in my eye now! If this form is that slow on my home PC (i7@4GHz and a good graphic card) what it will do tommorow on the old P4 computer at work?

I even tried to use the code below but it does absoloutly nothing, if it is not slowing it down more!

private void FilterForm_ResizeBegin(object sender, EventArgs e)
{
    foreach(TableLayoutPanel tlp in panelFilters.Controls)
    {
        if(tlp != null)
        {
            tlp.SuspendLayout();
        }
    }
}

private void FilterForm_ResizeEnd(object sender, EventArgs e)
{
    foreach (TableLayoutPanel tlp in panelFilters.Controls)
    {
        if (tlp != null)
        {
            tlp.ResumeLayout();
        }
    }
}

Please let me know if there is a trick to make tablelayoutpanel to work faster...or if you know a better approach to lay down about hundred of controls nicely aligned.


回答1:


Use this code.

public class CoTableLayoutPanel : TableLayoutPanel
{
    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText, true);
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= NativeMethods.WS_EX_COMPOSITED;
            return cp;
        }
    }

    public void BeginUpdate()
    {
        NativeMethods.SendMessage(this.Handle, NativeMethods.WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
    }

    public void EndUpdate()
    {
        NativeMethods.SendMessage(this.Handle, NativeMethods.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);
        Parent.Invalidate(true);
    }
}

public static class NativeMethods
{
    public static int WM_SETREDRAW = 0x000B; //uint WM_SETREDRAW
    public static int WS_EX_COMPOSITED = 0x02000000; 


    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); //UInt32 Msg
}



回答2:


If you create a new class derived from TableLayoutPanel and set the ControlStyles such that DoubleBuffered is true, your performance will improve dramatically.

public class MyPanel :  TableLayoutPanel
{
    public MyPanel()
    {
        this.SetStyle(ControlStyles.DoubleBuffer, true);
    }

}


来源:https://stackoverflow.com/questions/8900099/tablelayoutpanel-responds-very-slowly-to-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!