NinethSense oWnZ mE!: Praveen’s drawing book

Choose a Topic:

Mon
17
Sep '07

Move a control with mouse on form

This is a simple script which demonstates how to move a control (here I used button) by dragging it (without using builtin drag-drop features ;) )


 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        private int x = 0;
        private int y = 0;
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            x = e.X;
            y = e.Y;
        }
 
        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                button1.Left = (button1.Left + e.X) - x;
                button1.Top = (button1.Top +e.Y)-y;
            }
        }
    }
}
The CodeProject Microsoft Developer Network Official ASP.NET Forums Microsoft .NET Framework Community Microsoft Most Valuable Professional Kidoos forums Microsoft Visual Studio Developer Home Professional Information Technology Solutions Microsoft Research Home Kerala Microsoft Users Group Community Website