Search code examples
c#.netwindowspinvokemessaging

How to stop/suspend a form from painting in C#?


I am trying to figure out how to stop a form from paintingon screen. What I mean by this is when I launch the form it doesn't end up painting the form so that the interface is not displayed.

I know how to do this with controls but I cannot figure out how to do with a Form. I am thinking sending a message to stop it from painting would be the best option although I am unsure of which message would create the initial paint job.

Here is how to suspend a control from being painted.

using System.Runtime.InteropServices;

class DrawingControl
{
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, 
                                         bool wParam, Int32 lParam);

    private const int WM_SETREDRAW = 11;

    public static void SuspendDrawing(Control parent)
    {
        SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
    }

    public static void ResumeDrawing(Control parent)
    {
        SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
        parent.Refresh();
    }
}

Solution

  • I figured out the answer to my question. It was as simple as sending a message to stop the painting from happening and adding it to both the the InitializeComponent() and OnPaint().

    Adding it to just InitializeComponent() will paint the form, but immediately suspend it. Adding it to just onPaint seems to do nothing, so the winner was both.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication11
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                SuspendDrawing(this);
            }
    
            [DllImport("user32.dll")]
            public static extern int SendMessage(IntPtr hWnd, Int32 wMsg,
                                                 bool wParam, Int32 lParam);
    
            private const int WM_SETREDRAW = 11;
            private const int WM_PAINT = 0xf;
            private const int WM_CREATE = 0x1;
    
            public static void SuspendDrawing(Form parent)
            {
                SendMessage(parent.Handle, WM_PAINT, false, 0);
            }
    
            public static void ResumeDrawing(Form parent)
            {
                SendMessage(parent.Handle, WM_PAINT, true, 0);
             //   parent.Refresh();
            }
    
            protected override void OnPaint(PaintEventArgs e)
            {
                SuspendDrawing((this));
            }
    
        }
    }