유용한 정보

[C#] 임의의 컨트롤을 사용하여 폼을 이동하자

DevReff 2025. 4. 16. 04:53
728x90
728x90
SMALL

1. 소스
/// <summary>
/// WinForm에서 사용자가 정의한 타이틀바에 의해서 폼을 이동 한다.
/// </summary>
/// <param name="form">폼</param>
/// <param name="triggerControls">사용자정의 타이틀바에 속해 있는 컨트롤목록</param>
/// <param name="movingCursorOrNull">마우스커서</param>

void SetMovingForm(this Form form, Control[] triggerControls, Cursor movingCursorOrNull = null)
{
bool mouseDown = false;
Point lastMousePoint = new Point();
Cursor movingCursor;

if (movingCursorOrNull == null)
movingCursor = Cursors.NoMove2D;
else
movingCursor = movingCursorOrNull;

Dictionary<Control, Cursor> oldCursors = new Dictionary<Control, Cursor>();

foreach (var item in triggerControls)
{
Control con = item;
try
{
con.MouseDown += (s, e) =>
{
var thisControl = s as Control;

mouseDown = true;

if (!oldCursors.ContainsKey(item))
oldCursors.Add(item, thisControl.Cursor);
else
oldCursors[item] = thisControl.Cursor;

thisControl.Cursor = movingCursor;

lastMousePoint = Control.MousePosition;
};

con.MouseMove += (s, e) =>
{
if (!mouseDown)
return;

Point currentPoint = Control.MousePosition;

int x = currentPoint.X - lastMousePoint.X;
int y = currentPoint.Y - lastMousePoint.Y;

form.Location = new Point(form.Location.X + x, form.Location.Y + y);

lastMousePoint = currentPoint;
};

con.MouseUp += (s, e) =>
{
var thisControl = s as Control;

mouseDown = false;

if (oldCursors != null && oldCursors.ContainsKey(thisControl))
thisControl.Cursor = oldCursors[thisControl];
};
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
}
}

반응형

2. 사용예제

    SetMovingForm(this, new Control[] { this, this.LBL_TITLE, Label1 }, Cursors.Hand);

728x90
728x90
LIST