Search code examples
c#winformsminimize

Minimized application showing above the task bar


I have an application that I do not want to show in the taskbar. When the application is minimized it minimizes to the SysTray.

The problem is, when I set ShowInTaskbar = false the minimized application shows above the task bar, just aboe the Windows 7 start button. If I set ShowInTaskbar = true the application minimizes correctly, but obviously the application shows in the taskbar.

Any idea why this is happening and how I can fix it?

Failure to minimize

EDIT: For the sake of clarity, here is the code I'm using:

private void Form1_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized) {                                                                                    
                this.Hide(); 
                this.Visible = false;         
                notifyIcon1.Visible = true;           
            }
            else
            {
                notifyIcon1.Visible = false; 
            }
        }

    private void btnDisable_Click(object sender, EventArgs e)
    {

        // Minimize to the tray
        notifyIcon1.Visible = true;
        WindowState = FormWindowState.Minimized; // Minimize the form
    }

Solution

  • There is no event handler to establish when a form's minimise request has been fired. So to 'get in' before the form has been minimised you'll have to hook into the WndProc procedure

    private const int WM_SYSCOMMAND = 0x0112;
    private const int SC_MINIMIZE = 0xF020; 
    
    [SecurityPermission(SecurityAction.LinkDemand, 
                        Flags = SecurityPermissionFlag.UnmanagedCode)]
    protected override void WndProc(ref Message m)
    {
        switch(m.Msg)
        {
            case WM_SYSCOMMAND:
                int command = m.WParam.ToInt32() & 0xfff0;
                if (command == SC_MINIMIZE && this.minimizeToTray)
                {
                    PerformYourOwnOperation();  // For example
                }
                break;
        }
        base.WndProc(ref m);
    }
    

    and then you can merely hide the form in the PerformYourOwnOperation(); method

    public void PerformYourOwnOperation()
    {
        Form form = GetActiveForm();
        form.Hide();
    }
    

    You will then need some mechanism to Show() the hidden form otherwise it will be lost.

    Another way is using the the form's resize event. However, this fires after the form is minimised. To do this you can do something like

    private void Form_Resize(object sender, EventArgs e)
    {
        if (WindowState == FormWindowState.Minimized)
        {
            // Do some stuff.
        }
    }
    

    I hope this helps.