Windows Taskbar Location

I was working on a form window today that pops up from windows tray area and I wanted it to have a different location depending on taskbar dock location.

So again I find lots of people using API (SHAppBarMessage) and other sloppy solutions and came up with my own idea to simply compare Screen.PrimaryScreen.WorkingArea with Screen.PrimaryScreen.Bounds.

Here is my code:
        private enum TaskBarLocation { Left, Right, Top, Bottom, Hidden };
        private TaskBarLocation GetLocation()
        {
            Rectangle taskBarRect = Rectangle.Intersect(Screen.PrimaryScreen.WorkingArea, Screen.PrimaryScreen.Bounds);

            if (taskBarRect.Width == Screen.PrimaryScreen.Bounds.Width)
            {
                return taskBarRect.Y == 0 ? TaskBarLocation.Bottom : TaskBarLocation.Top;
            }
            else if (taskBarRect.Height == Screen.PrimaryScreen.Bounds.Height)
            {
                return taskBarRect.X == 0 ? TaskBarLocation.Right : TaskBarLocation.Left;
            }
            else
            {
                return TaskBarLocation.Hidden;
            }
        }
Then to set window location:
                switch (GetLocation())
                {
                    case TaskBarLocation.Left:
                        this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Left, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
                        break;
                    case TaskBarLocation.Top:
                        this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Top);
                        break;
                    case TaskBarLocation.Right:
                    case TaskBarLocation.Bottom:
                    default:
                        this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
                        break;
                }


Enjoy!

Proper way to handle FormClosing event

Most common way to minimize an application is to override the FormClosing event by setting e.Handled = true; and then proceed to set form as hidden.

This creates a problem when the operating system want to close your application. The application simply refuses to close.

There are lots of solutions for this and in the past I've implemented an override to WndProc() and checked for WM_CLOSE message. This is not a very clean solution.

Today I found e.CloseReason and it's a beauty!

Check this out:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
 if (e.CloseReason == CloseReason.UserClosing)
 {
  // Minimize to system tray
  e.Cancel = true;
  this.Visible = false;
  this.notifyIcon1.Visible = true;
 }
}
The above solution will handle system shutdown etc etc.

It is also a very clean solution for MDI windows that you simply want to hide.