在做MDI程式時有時需要子窗體不能重複打開,有時有人還需要使子窗體隻能在父窗體範圍内移動,即不超出父窗體的範圍,不出現滾動條!

防止子窗體重複彈出,網上很多類似。使子窗體在父窗體範圍内移動,我想到一個暫時的解決方案,即在定義一個子窗體的時候,順帶定義一個子窗體的移動事件,使它隻能在父窗體的範圍内移動。
代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//靜态定義窗體,可以使它儲存住狀态
private static Form2 form2;
private void 窗體一ToolStripMenuItem_Click(object sender, EventArgs e)
{
//防止重複打開子窗體
if (form2 == null || form2.IsDisposed)
{
form2 = new Form2();
form2.MdiParent = this;
form2.Show();
//自定義窗體移動事件使它移動時不超過父窗體邊界
form2.Move += new EventHandler(form2_Move);
}
}
private void form2_Move(object sender, EventArgs e)
{
//讓窗體不超過上邊界
if (form2.Location.Y < 0)
{
form2.Location = new Point(form2.Location.X, 0);
}
//讓窗體不超過左邊界
if (form2.Location.X < 0)
{
form2.Location = new Point(0, form2.Location.Y);
}
//讓窗體不超過右邊界,同時也防止子窗體比父窗體寬時産生錯誤
//如果子窗體比父窗體寬會和上一條件if (form2.Location.X < 0)産生二義性使窗體産生振動
if (form2.Location.X > this.Size.Width - form2.Size.Width - 12 && form2.Location.X > 0)
{
form2.Location = new Point(this.Size.Width - form2.Size.Width - 12, form2.Location.Y);
}
//讓窗體不超過下邊界,同時也防止子窗體比父窗體高時産生錯誤
//錯誤同上
if (form2.Location.Y > this.Size.Height - form2.Size.Height - 55 && form2.Location.Y > 0)
{
form2.Location = new Point(form2.Location.X, this.Size.Height - form2.Size.Height - 55);
}
}
}
}
ps.在普通化父窗體時,把子窗體往下或往右貌似怎麼都會有滾動條,而最大化後,需要往右或往下的限制寬度和高度都要比我正常想的要多出一些數字,我也搞不懂,限制往右需要多減12,限制往下需要多減55,是因為子窗體邊框的原因!?使用無标題欄的父窗體則可消除這些問題!