Prevent redrawing of controls on resize for Windows Forms

前端 未结 3 1729
[愿得一人]
[愿得一人] 2021-01-01 07:00

I have a TableLayoutPanel which holds a dynamic number of controls inside a SplitterPanel. A user may want to resize the panel to fit these Controls to avoid use of a scrol

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 07:45

    As Hans commented, SuspendLayout and ResumeLayout work well in this situation, along with Suspending the drawing of the control for the container:

    public static class Win32 {
    
      public const int WM_SETREDRAW = 0x0b;
    
      [DllImport("user32.dll")]
      public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    
      public static void SuspendPainting(IntPtr hWnd) {
        SendMessage(hWnd, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
      }
    
      public static void ResumePainting(IntPtr hWnd) {
        SendMessage(hWnd, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
      }
    }
    

    Then from you resize events:

    private void Form1_ResizeBegin(object sender, EventArgs e) {
      tableLayoutPanel1.SuspendLayout();
    }
    
    private void Form1_ResizeEnd(object sender, EventArgs e) {
      Win32.SuspendPainting(tableLayoutPanel1.Handle);
      tableLayoutPanel1.ResumeLayout();
      Win32.ResumePainting(tableLayoutPanel1.Handle);
      this.Refresh();
    }
    

提交回复
热议问题