日期:2014-05-18 浏览次数:20916 次
bool down = false; private void button10_MouseMove(object sender, MouseEventArgs e) { if (!down) return; Point p = button10.PointToScreen(button10.Location); Point p1 = button10.PointToScreen(e.Location); button10.Left = button10.Left + (p1.X - p.X); button10.Top = button10.Top + (p1.Y - p.Y); this.Update(); } private void button10_MouseDown(object sender, MouseEventArgs e) { down = true; } private void button10_MouseUp(object sender, MouseEventArgs e) { down = false; }
------解决方案--------------------
// C#鼠标拖动任意控件 Point p = new Point(0, 0); //利用Windows的API函数:SendMessage 和 ReleaseCapture const uint WM_SYSCOMMAND = 0x0112; const uint SC_MOVE = 0xF010; const uint HTCAPTION = 0x0002; [DllImport("user32.dll", EntryPoint = "SendMessageA")] private static extern int SendMessage(IntPtr hwnd, uint wMsg, uint wParam, uint lParam); [DllImport("user32.dll")] private static extern int ReleaseCapture(); public void MouseDown(object sender, MouseEventArgs e) { Button bt = sender as Button; ReleaseCapture(); SendMessage((sender as Control).Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);} public void bt_MouseMove(object sender, MouseEventArgs e) { Button bt = sender as Button; if (e.Button == MouseButtons.Left) { bt.Location = new Point(bt.Left + e.X - p.X, bt.Top + e.Y - p.Y); } }
------解决方案--------------------
创建一个panel,两个button(button的移动类似)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace 实现panel的拖动和缩放 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Point p = new Point(0, 0);//定义一个点 //并为控件 添加 MouseDown 事件 // C#鼠标拖动任意控件 //利用Windows的API函数:SendMessage 和 ReleaseCapture const uint WM_SYSCOMMAND = 0x0112; const uint SC_MOVE = 0xF010; const uint HTCAPTION = 0x0002; [DllImport("user32.dll", EntryPoint = "SendMessageA")] private static extern int SendMessage(IntPtr hwnd, uint wMsg, uint wParam, uint lParam); [DllImport("user32.dll")] private static extern int ReleaseCapture(); int xx = 0; private void addpanel_Click(object sender, EventArgs e) {//创建panel xx++; CreateControls.CreatePanel(backpanel, xx.ToString(), panel_MouseMove, panel_MouseDown, panel_Paint); } public void panel_Paint(object sender, PaintEventArgs e) { Panel panel = sender as Panel; ControlPaint.DrawBorder(e.Graphics,