본문 바로가기

프로그래밍/C#, WPF, Winform

[WPF] 자석 기능(Sticky) 윈도우





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
 
namespace NPMon_WPF.Widget
{
    /// <summary>
    /// WidgetStatus.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class WidgetStatus : Window
    {
        public WidgetStatus()
        {
            InitializeComponent();
 
            this.MouseLeftButtonUp += OnMouseLeftButtonUp;
        }
 
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                this.DragMove();
        }
 
        private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            int offset = 25;
 
            foreach (Screen scr in Screen.AllScreens)
            {
                if (Math.Abs(scr.WorkingArea.Left - this.Left) < offset)
                    this.Left = scr.WorkingArea.Left;
                else if (Math.Abs(this.Left + this.ActualWidth - scr.WorkingArea.Left - scr.WorkingArea.Width) < offset)
                    this.Left = scr.WorkingArea.Left + scr.WorkingArea.Width - this.ActualWidth;
 
                if (Math.Abs(scr.WorkingArea.Top - this.Top) < offset)
                    this.Top = scr.WorkingArea.Top;
                else if (Math.Abs(this.Top + this.ActualHeight - scr.WorkingArea.Top - scr.WorkingArea.Height) < offset)
                    this.Top = scr.WorkingArea.Top + scr.WorkingArea.Height - this.ActualHeight;
            }
        }
 
    }
}
 
cs