簡體   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