티스토리 뷰
Drag select multiple controls
C# 마우스 드래그해서 여러개 콘트롤 선택하기
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace DragSelectMultipleControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
}
private Point selectionStart;
private Point selectionEnd;
private Rectangle selection;
private bool mouseDown;
private void GetSelectedTextBoxes()
{
List<TextBox> selected = new List<TextBox>();
foreach (Control c in Controls)
{
if (c is TextBox)
{
if (selection.IntersectsWith(c.Bounds))
{
selected.Add((TextBox)c);
}
}
}
MessageBox.Show("you selected " + selected.Count + "textbox controls");
}
protected override void OnMouseDown(MouseEventArgs e)
{
selectionStart = PointToClient(MousePosition);
mouseDown = true;
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
mouseDown = false;
SetSelectionRect();
Invalidate();
GetSelectedTextBoxes();
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (!mouseDown)
return;
selectionEnd = PointToClient(MousePosition);
SetSelectionRect();
Invalidate();
base.OnMouseMove(e);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(mouseDown)
{
using (Pen pen = new Pen(Color.Black, 1F))
{
pen.DashStyle = DashStyle.Dash;
e.Graphics.DrawRectangle(pen, selection);
}
}
}
private void SetSelectionRect()
{
int x, y;
int width, height;
x = selectionStart.X > selectionEnd.X ? selectionEnd.X : selectionStart.X;
y = selectionStart.Y > selectionEnd.Y ? selectionEnd.Y : selectionStart.Y;
width = selectionStart.X > selectionEnd.X ? selectionStart.X - selectionEnd.X : selectionEnd.X - selectionStart.X;
height = selectionStart.Y > selectionEnd.Y ? selectionStart.Y - selectionEnd.Y : selectionEnd.Y - selectionStart.Y;
selection = new Rectangle(x, y, width, height);
}
}
}
'프로그래밍 > C#' 카테고리의 다른 글
c# 윈도우 로그인 계정 얻기 (0) | 2019.01.22 |
---|---|
C# TrackPopup 처리(마우스 우클릭시 메뉴처리) (0) | 2018.12.18 |
C# Tutorial - Drag & Drop controls (0) | 2018.12.18 |
c# 핑퐁게임 소스코드 (0) | 2018.12.17 |
C# 윈폼에서 WPF 폼 만드는 방법 (0) | 2018.12.06 |