繁体   English   中英

如何使Windows窗体的四个角始终在桌面上可见?

[英]How to keep four corners of windows form visible all time on desktop?

我有一个Windows窗体,正在用作桌面应用程序。 现在,我希望该表单在拖动时不要超出桌面边框。 我知道整个窗口不会消失,但我想显示所有四个角。 我设置了“边框样式=固定工具窗口”,并进行了编码以编程方式移动表格。

所以代替这个:

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

我要这个:

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

您可以使用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;
}

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

这将在屏幕上保留表单的“四个”角

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

您要避免窗口(winforms MainForm)不离开屏幕吗? 如果是这种情况,您将无法在“移动窗体”事件中进行处理,并且在移动时检查“左移”属性是否为负数会返回该方法。 而且,如果您知道表格的大小和分辨率,就可以计算出正确的和正确的底数。

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

这样的事情。 未经测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM