表單可在多螢幕間自由拖曳;當 PictureBox 控制項大部分進入某螢幕時,自動將表單對齊至該螢幕工作區。
Screen.AllScreens:取得所有顯示器資訊Screen.GetWorkingArea(control):取得控制項所在螢幕的工作區Screen.FromControl(control):直接取得控制項所在的 Screen 物件
public partial class MainForm : Form {
private Point _dragOffset;
private Rectangle[] _screenRects;
public MainForm() {
InitializeComponent();
this.MouseDown += (s, e) => {
if (e.Button == MouseButtons.Left) {
_dragOffset = new Point(e.X, e.Y);
this.MouseMove += Form_MouseMove;
}
};
this.MouseUp += (s, e) => this.MouseMove -= Form_MouseMove;
}
private void Form_MouseMove(object sender, MouseEventArgs e) {
this.Location = new Point(
this.Location.X + e.X - _dragOffset.X,
this.Location.Y + e.Y - _dragOffset.Y
);
}
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
_screenRects = Array.ConvertAll(Screen.AllScreens, s => s.WorkingArea);
}
protected override void OnMove(EventArgs e) {
base.OnMove(e);
// PictureBox 佔表單 1/4,判斷其中心點落在哪個螢幕
var pbCenter = new Point(
pictureBox1.Left + pictureBox1.Width / 2,
pictureBox1.Top + pictureBox1.Height / 2
);
var screen = Screen.FromControl(pictureBox1);
if (screen != null) {
// 可選:將表單移至該螢幕工作區內
// this.Location = new Point(screen.WorkingArea.Left, this.Location.Y);
}
}
}
const int SNAP_DIST = 20;
private void SnapToScreen() {
foreach (var scr in Screen.AllScreens) {
var wa = scr.WorkingArea;
if (Math.Abs(this.Left - wa.Left) < SNAP_DIST) this.Left = wa.Left;
if (Math.Abs(this.Top - wa.Top) < SNAP_DIST) this.Top = wa.Top;
if (Math.Abs(this.Right - wa.Right) < SNAP_DIST) this.Left = wa.Right - this.Width;
if (Math.Abs(this.Bottom - wa.Bottom) < SNAP_DIST) this.Top = wa.Bottom - this.Height;
}
}
在 OnMove 或 OnResizeEnd 呼叫 SnapToScreen()。
AutoScaleMode = Dpi 或在 app.manifest 宣告 dpiAwareScreen.WorkingArea 回傳裝置獨立像素,配合 DPI 縮放正確善用 Screen 類別與滑鼠事件,即可實作流暢的多螢幕 WinForms 體驗。