퇴근5분전

 

  화면에 컨트롤을 여러개 뿌려져있을때

이를 마우스 드래그로 여러개를 선택하고자 할때 점선으로 박스를 그리고 싶을때 사용하면 됨.

 

기본 form에 버튼 몇개를 마구잡이로 배치하고 아래와 같이 구현하면

 

마우스 down시작점에서 마우스 up끝점까지 박스를 그려준다.

 

시작점에서 끝지점이 w+, h+일때는 크게 문제가 안되지만.

끝지점이 w- 또는 h-일 경우  Rectangle GetBox(Rectangle rct) 메서드 내에 있는 것처럼

박스위치와 크기를 고쳐줘야 한다.

 

전에 모니터링 만들땐 좀 복잡하게 했던것 같은뎅... 어째꺼나.. 아래처럼 쉽게 되었다.

 

 

어느 방향으로든 마우스로 끌어도 사각형이 제대로 그려진다.

 

 

 

 

List<Button> SelectButtonList = new List<Button>();

        bool IsMDown = false;
        Rectangle rect = new Rectangle();
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            ClearSelectedButtonList();

            IsMDown = e.Button == System.Windows.Forms.MouseButtons.Left;
            rect.Location = e.Location;
            rect.Width = 0;
            rect.Height = 0;
            Invalidate();
        }

        private void ClearSelectedButtonList()
        {
            foreach (var btn in SelectButtonList)
            {
                btn.ForeColor = Color.Black;
            }
            SelectButtonList.Clear();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (IsMDown)
            {
                rect.Width = e.Location.X - rect.X;
                rect.Height = e.Location.Y - rect.Y;
                Invalidate();
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);

            IsMDown = false;

            Rectangle box = GetBox(rect);

            foreach (Control ctrl in Controls)
            {
                if (box.Contains(ctrl.Bounds) && ctrl is Button)
                {
                    SelectButtonList.Add(ctrl as Button);
                    ctrl.ForeColor = Color.Red;
                }
            }

            rect.Location = e.Location;
            rect.Width = 0;
            rect.Height = 0;

            Invalidate();
        }

 

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
             Rectangle box = GetBox(rect);
             ControlPaint.DrawBorder(e.Graphics, box, Color.Red, ButtonBorderStyle.Dotted);
        }

 

        private Rectangle GetBox(Rectangle rct)
        {
            Rectangle box = rct;

            if (box.Width < 0)
            {
                box.X = box.X + box.Width;
                box.Width *= -1;
            }

            if (box.Height < 0)
            {
                box.Y = box.Y + box.Height;
                box.Height *= -1;
            }
            return box;
        }