Freigeben über


Hidden Forms Windows

Trying to hide your forms window? Here are a couple sample solutions:

One cumbersome solution is to override WndProc, listen for any window position changing messages (which includes z-order), and then not pass any show window flag on.

public class MyForm : Form
{
    public MyForm()
    {
        // Ensure that this is a hidden window
        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
        this.FormBorderStyle = FormBorderStyle.None;
    }

    protected override void WndProc(ref Message m)
    {
        const uint WM_WINDOWPOSCHANGING = 0x0046; // WinUser.h
        const uint SWP_SHOWWINDOW       = 0x0040; // WinUser.h

        if (m.Msg == WM_WINDOWPOSCHANGING)
        {
            // Ensure the window is hidden by consuming any "show window" requests
            // (which can happen when pressing alt+tab)
            Win32Api.WINDOWPOS windowPos = (Win32Api.WINDOWPOS)Marshal.PtrToStructure(m.LParam, typeof(Win32Api.WINDOWPOS));
            windowPos.flags &= unchecked(~SWP_SHOWWINDOW);
            Marshal.StructureToPtr(windowPos, m.LParam, true);
            m.Result = (IntPtr)0;
        }

        base.WndProc(ref m);
    }
}

The better solution is to simply make the window not visible after it finishes loading:

public class MyForm : Form
{
    public MyForm()
    {
        // Ensure that this is a hidden window
        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
        this.FormBorderStyle = FormBorderStyle.None;

        this.Load += new EventHandler(MyForm_Load);
    }

    void MyForm_Load(object sender, EventArgs e)
    {
        this.Visible = false;
    }
}