C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Methods:
WorkingArea.Height:
This returns the height of the screen minus the taskbar in pixels.
WorkingArea.Width:
Width of screen, minus the Vista sidebar or anything else.
Height:
This is the height of your window in pixels.
Width:
This is the width of the window in pixels.
Location:
Top left corner of the form in pixels relative to the screen.
X and Y:
Horizontal and vertical coordinates of Point.
Here: We see the approach we will use to position windows like a palette relative to another window. This will position to the bottom.
Info: The example shows how to get the sizes of both windows. We must know the positions and sizes of both windows we want to position.
So: We must get the size of the working area, meaning the size of the user's desktop minus the taskbar. We use the WorkingArea class for this.
Finally: Before we place the form, we need to make sense that our new position makes sense. Then we place the new Form.
C# program that positions a sub-window
/// <summary>
/// A Windows Form.
/// </summary>
public partial class MainWindow : Form
{
/// <summary>
/// The Windows Form we want to position.
/// </summary>
ReporterWindow _reporterWin = new ReporterWindow();
public MainWindow ()
{
InitializeComponent();
}
private void reportMoveToolStripMenuItem_Click(object sender, EventArgs e)
{
// This is an event handler triggered by a menu item (or button).
PositionReporterEdge(); // Position the window.
_reporterWin.Show();
}
/// <summary>
/// Position the "Reporter" form next to the current form.
/// </summary>
private void PositionReporterEdge()
{
int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
Point parentPoint = this.Location;
int parentHeight = this.Height;
int parentWidth = this.Width;
int childHeight = _reporterWin.Height;
int childWidth = _reporterWin.Width;
int resultX;
int resultY;
if ((parentPoint.Y + parentHeight + childHeight) > screenHeight)
{
// If we would move off the screen, position near the top.
resultY = parentPoint.Y + 50; // move down 50
resultX = parentPoint.X;
}
else
{
// Position on the edge.
resultY = parentPoint.Y + parentHeight;
resultX = parentPoint.X;
}
// set our child form to the new position
_reporterWin.Location = new Point(resultX, resultY);
}
}
Tip: You can add left, right and top if you need them. The method can be modified with additional features.
Also: I have used it for a "Find in this page" window, similar to Microsoft Word's.