Drag کردن کنترل به نقطه ای دلخواه از فرم
یک برنامه ویندوزی ایجاد کرده و به عنوان مثال یک کنترل TextBox بر روی ان قرار دهید، سپس کدهای زیر را در رویداد Load فرم و MouseMove ،MouseDown و MouseUp کنترل textBox بنویسید :
using System; using System.Drawing; using System.Windows.Forms; namespace DragTextbox { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Control activeControl; private Point previousLocation; private void Form1_Load(object sender, EventArgs e) { var textbox = new TextBox(); textbox.Location = new Point(50, 50); textbox.MouseDown += new MouseEventHandler(textBox1_MouseDown); textbox.MouseMove += new MouseEventHandler(textBox1_MouseMove); textbox.MouseUp += new MouseEventHandler(textBox1_MouseUp); } private void textBox1_MouseDown(object sender, MouseEventArgs e) { activeControl = sender as Control; previousLocation = e.Location; Cursor = Cursors.Hand; } private void textBox1_MouseMove(object sender, MouseEventArgs e) { if (activeControl == null || activeControl != sender) return; var location = activeControl.Location; location.Offset(e.Location.X - previousLocation.X, e.Location.Y - previousLocation.Y); activeControl.Location = location; } private void textBox1_MouseUp(object sender, MouseEventArgs e) { activeControl = null; Cursor = Cursors.Default; } } }
حال برنامه را اجرا کرده و با ماوس کنترل را به نقطه دلخواه جابه جا کنید.