C# Winform平台下实现自由拖拽控件

C#控件拖动

1.场景需求

有时候,我们在编写PC上位机软件的时候,不免需要将所定义的控件可以自由的拖拽到任意地方。为了实现此一需求,我尝试了很多种方法,比如使用Mouse_Leave,Mouse_Down等方法,最后实际测试发现这样的实现的拖动,会导致控件在不断的闪烁,而且效果极差。因此在遍寻了很久之后,终于找到了解决方法。特将此记录下来,以资后用。

2.winform平台的标准拖拽事件

在类中引入标准拖拽事件的动态链接库

//window标准拖拽事件
 [DllImport("user32.dll", EntryPoint = "ReleaseCapture")]
 public static extern void ReleaseCapture();
 [DllImport("user32.dll", EntryPoint = "SendMessage")]
public static extern void SendMessage(int hwnd, int wMsg, int wParam, int lParam);

3.实现控件的MouseDown方法

private void ActionServo1_MouseDown(object sender, MouseEventArgs e)
 {
    
    
      if (e.Button == MouseButtons.Left)
      {
    
    
          ActionServo1.BringToFront(); //将控件置于顶层
          ReleaseCapture();
          SendMessage((int)ActionServo1.Handle, 0xA1, 2, 0);
          //Console.WriteLine(ActionServo1.Location.X+"--"+ ActionServo1.Location.Y);
       }
 }

到这里你已经实现控件的拖拽了,是不是很简单。

4.注意事项

在使用过程中,发现向GroupBox这种控件不支持拖动呢。

猜你喜欢

转载自blog.csdn.net/qq_41020634/article/details/105752773