Realize free drag and drop control under C# Winform platform

C# control dragging

1. Scenario requirements

Sometimes, when we write PC host computer software, we inevitably need to freely drag and drop the defined controls to any place. In order to achieve this requirement, I tried many methods, such as using Mouse_Leave, Mouse_Down and other methods. Finally, the actual test found that such an implementation of dragging would cause the control to flicker continuously, and the effect was extremely poor. So after searching for a long time, I finally found a solution. This is recorded here for future use.

2. Standard drag and drop event of winform platform

Introduce the dynamic link library of the standard drag and drop event in the class

//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. Implement the MouseDown method of the control

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);
       }
 }

So far you have implemented the drag and drop of the control, isn't it very simple.

4. Precautions

During use, I found that controls such as GroupBox do not support dragging.

Guess you like

Origin blog.csdn.net/qq_41020634/article/details/105752773