SoFunction
Updated on 2025-03-06

C# method to implement mouse drag and drop a frameless floating form

introduce

Generally speaking, holding down the left mouse button in the title bar can achieve the drag operation.

When a floating form is used, if the form border is included, the interface will give the user a feeling that the user will be unfriendly, so the floating form has no borders. However, for such a form without borders, how to drag and drop?

It is mainly used to implement two API functions of Windows, namely ReleaseCapture and SendMessage:

(1)ReleaseCapture function

This function is used to release the cursor captured by a window in the current thread. The syntax format is as follows:

[DllImport("")]
public static extern bool ReleaseCapture();

(2)SendMessage function

This function is used to send Windows messages to the specified form. The syntax format is as follows:

[DllImport("")]
public static extern bool SendMessage(IntPtr hwdn,int wMsg,int mParam,int lParam);

(3) Example

In this example, the mouse drops on the form. Before UP, drag and drop the form to any position.

//------------------------------------------------------------------------------
// <auto-generated>
// This code is generated by the tool.// Runtime version: 4.0.30319.42000//
// Changes to this file may cause incorrect behavior and if// Regenerate the code and these changes will be lost.// </auto-generated>
//------------------------------------------------------------------------------
 
namespace _198.Properties {
    using System;
    
    
    /// <summary>
    /// A strongly typed resource class used to find localized strings, etc.    /// </summary>
    // This class is by StronglyTypedResourceBuilder    // The class is automatically generated through a tool similar to ResGen or Visual Studio.    // To add or remove members, edit the .ResX file and rerun ResGen    // (use /str as command option), or regenerate the VS project.    [global::("", "17.0.0.0")]
    [global::()]
    [global::()]
    internal class Resources {
        
        private static global:: resourceMan;
        
        private static global:: resourceCulture;
        
        [global::("", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }
        
        /// <summary>
        /// Returns the cached ResourceManager instance used by this class.        /// </summary>
        [global::(global::)]
        internal static global:: ResourceManager {
            get {
                if ((resourceMan, null)) {
                    global:: temp = new global::("_198.", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
        
        /// <summary>
        /// Rewrite the CurrentUICulture property of the current thread, for        /// Perform rewrite using all resource lookups for this strongly typed resource class.        /// </summary>
        [global::(global::)]
        internal static global:: Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
        
        /// <summary>
        /// Find a localized resource of type.        /// </summary>
        internal static  _04 {
            get {
                object obj = ("_04", resourceCulture);
                return (()(obj));
            }
        }
    }
}

2.

namespace _198
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private  components = null;
 
        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                ();
            }
            (disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            SuspendLayout();
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = ;
            BackgroundImage = ._04;
            BackgroundImageLayout = ;
            ClientSize = new Size(311, 218);
            FormBorderStyle = ;
            Name = "Form1";
            Text = "Form1";
            MouseDown += Form1_MouseDown;
            ResumeLayout(false);
        }
 
        #endregion
    }
}

3.

In the example, the API function [DllImport("")] used will prompt the error message of CA1401 and SYSLIB1054, ignore it, otherwise the generated form cannot be dragged and dropped. Logically speaking, after following the prompts, P/INVOKE should work normally, but I am not in the mood to debug it. Interested netizens can study it in depth and overcome it. There will be results for them. Please reply. The framework I use is .NET 8.0.

// Drag and drop the frameless floating formusing ;
namespace _198
{
    public partial class Form1 : Form
    {
        #region API functions used in this program        [DllImport("")]
        public static extern bool ReleaseCapture();// Used to release the cursor captured by a window in the current thread        [DllImport("")]
        public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam);//Send Windows messages to the specified form        #endregion
 
        #region Variables that need to be declared in this program        public const int WM_SYSCOMMAND = 0x0112;    //This variable indicates the type of message to be sent to Windows        public const int SC_MOVE = 0xF010;          //This variable represents the additional message to send the message        public const int HTCAPTION = 0x0002;        //This variable represents the additional message to send the message        #endregion
 
        public Form1()
        {
            InitializeComponent();
        }
        /// &lt;summary&gt;
        /// The mouse falls on the form and drags it at will        /// &lt;/summary&gt;
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();                                                                                       // Used to release the cursor captured by a window in the current thread            SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); //Send a message to Windows to drag the form        }
    }
}

The above is the detailed content of C#’s method of dragging and dropping a frameless floating form with a mouse. For more information about C#’s frameless floating form, please pay attention to my other related articles!