2012-08-22 55 views
1

我有一个窗体,我用作桌面应用程序。 现在我希望表单在拖动时不应超出桌面边界。 我知道整个窗口不会消失,但我想显示所有四个角落。 我已经设置了“边框样式=固定工具窗口”,并编码以编程方式移动窗体。如何在桌面上始终保持窗体四角可见?

因此,不是这样的:

 
---------------------- 
!     ! 
!   --------------- 
!   !    ! 
!   !    ! 
!   --------------- 
!     ! 
---------------------- 

我想这一点:

 

------------------------ 
!      ! 
!   -------------! 
!   !   !! 
!   !   !! 
!   -------------! 
!      ! 
------------------------ 
+0

图片无法正常显示请避开它们谢谢 –

+2

究竟我在看什么? – mtijn

+0

我不同意改变Windows的行为,因为用户期望它。通常,用户可以将窗口从屏幕上滑出(或将其移动到另一个屏幕),更改该行为可能会使用户感到不安。所以,我不会这么做,除非有很好的理由来改变Windows上Windows的预期行为。 –

回答

3

可以使用LocationChanged事件,并进行比较到Screen.AllScreens[0].Bounds这是主显示器,如果您有多个显示器,您可以更改索引以选择您将窗体限制在哪个屏幕上。

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; 
} 
+0

非常感谢.. !! –

+0

@ user1611002很乐意帮忙 –

+0

对于多台显示器,您可以使用'Screen.FromHandle(Handle)'来使用当前窗口的屏幕。 – Apache

0

如果我没有理解这个问题很好。

你想避免你的窗口(WinForms的MainForm)不离开屏幕? 如果是这种情况,你不能在事件内处理这个事件:移动表格 并在移动时检查Top en Left属性,如果这些属性变为负数,则返回该方法。 如果您知道您的表单有多大,并且您的解析度可以计算出右侧和底部。

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; 
    } 

就是这样。 未经测试。

2

比较形式界限与SytemInformation.VirtualScreen

例子:

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; 
    } 

这将保持一种形式的“四个”角落屏幕