I have a windows form which I am using as a desktop application. Now I want that the form should not go outside desktop borders when I drag it. I know that the whole window doesnt disappear but I want to display all four corners. I have set the "border style = Fixed Tool window",and coded to move form programmatically.
So instead of this:
---------------------- ! ! ! --------------- ! ! ! ! ! ! ! --------------- ! ! ----------------------
I want this:
------------------------ ! ! ! -------------! ! ! !! ! ! !! ! -------------! ! ! ------------------------
You can use the LocationChanged
event and compare it to Screen.AllScreens[0].Bounds
this is the primary monitor, if you have multiple monitors you could change then index to select which screen you limit your form to.
private void Form1_LocationChanged(object sender, EventArgs e)
{
if ((this.Left + this.Width) > Screen.AllScreens[0].Bounds.Width)
this.Left = Screen.AllScreens[0].Bounds.Width - this.Width;
if (this.Left < Screen.AllScreens[0].Bounds.Left)
this.Left = Screen.AllScreens[0].Bounds.Left;
if ((this.Top + this.Height) > Screen.AllScreens[0].Bounds.Height)
this.Top = Screen.AllScreens[0].Bounds.Height - this.Height;
if (this.Top < Screen.AllScreens[0].Bounds.Top)
this.Top = Screen.AllScreens[0].Bounds.Top;
}
Compare the forms bounds with SytemInformation.VirtualScreen
Example:
private void Form1_Move(object sender, EventArgs e)
{
KeepBounds();
}
private void KeepBounds()
{
if (this.Left < SystemInformation.VirtualScreen.Left)
this.Left = SystemInformation.VirtualScreen.Left;
if (this.Right > SystemInformation.VirtualScreen.Right)
this.Left = SystemInformation.VirtualScreen.Right - this.Width;
if (this.Top < SystemInformation.VirtualScreen.Top)
this.Top = SystemInformation.VirtualScreen.Top;
if (this.Bottom > SystemInformation.VirtualScreen.Bottom)
this.Top = SystemInformation.VirtualScreen.Bottom - this.Height;
}
this will keep the 'four' corners of a form in screen
If i understand the question good.
You want to avoid that you window (winforms MainForm) does not leave the screen? If this is the case, can't you handle this within the event Move of the Form and while moving check the Top en Left property if those become negative return the method. And if you know how large the your form is and you resolution you can calculate the right and bottom.
private void Move(object sender, EventArgs e)
{
var f = sender as Form;
var l = f.Left;
var t = f.Top;
var h = f.Height;
var w = f.Width;
var sh = Screen.GetWorkingArea(this).Height;
var sw = Screen.GetWorkingArea(this).Width;
if(t<0 || t+h > sh) return;
if (l < 0 || l+w > sw) return;
}
Something like this. Not tested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.